Changeset 184

Show
Ignore:
Timestamp:
08/17/07 21:55:43 (6 years ago)
Author:
cleverdevil
Message:

A first pass at has_many with a through and via keyword argument.

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • elixir/trunk/elixir/relationships.py

    r182 r184  
    138138``has_many`` relationship needs the foreign key created by the ``belongs_to``  
    139139relationship. 
     140 
     141There is an alternate form of the ``has_many`` relationship that takes only 
     142two keyword arguments: `through` and `via` in order to encourage a more 
     143rich form of many-to-many relationship that is an alternative to the  
     144``has_and_belongs_to_many`` statement.  Here is an example: 
     145 
     146:: 
     147 
     148    class Person(Entity): 
     149        has_field('name', Unicode) 
     150        has_many('assignments', of_kind='Assignment', inverse='person') 
     151        has_many('projects', through='assignments', via='project') 
     152 
     153    class Project(Entity): 
     154        has_field('title', Unicode) 
     155        has_many('assignments', of_kind='Assignment', inverse='project') 
     156 
     157    class Assignment(Entity): 
     158        has_field('start_date', DateTime) 
     159        belongs_to('person', of_kind='Person', inverse='assignments') 
     160        belongs_to('project', of_kind='Project', inverse='assignments') 
     161 
     162In the above example, a `Person` has many `projects` through the `Assignment` 
     163relationship object, via a `project` attribute. 
    140164 
    141165`has_and_belongs_to_many` 
     
    200224from elixir.fields      import Field 
    201225from elixir.entity      import EntityDescriptor, EntityMeta 
     226from sqlalchemy.ext.associationproxy import association_proxy 
    202227 
    203228import sys 
     
    499524    uselist = True 
    500525     
     526    def __init__(self, entity, name, *args, **kwargs): 
     527        if 'through' in kwargs and 'via' in kwargs: 
     528            setattr(entity, name, association_proxy(kwargs.get('through'), kwargs.get('via'))) 
     529            return 
     530         
     531        super(HasMany, self).__init__(entity, name, *args, **kwargs) 
     532     
    501533    def get_prop_kwargs(self): 
    502534        kwargs = super(HasMany, self).get_prop_kwargs()