try this:

    def attach_bar(self, bar):
          if getattr(self, "bars", None) is None:
              self.bars = []
          self.bars.append(bar)


On Mon, Feb 9, 2009 at 12:03 AM, Jack Orenstein <[email protected]> wrote:

>
> I have a model object that looks something like this:
>
>   class Foo(models.Model)
>       foo_id = models.IntegerField(primary_key = True)
>       xyz = models.CharField(max_length = 20)
>
> In my application, I'd like to add a list of Bar objects. It's like a
> foreign key, except that Bar objects don't exist in my databases. So
> I want a Foo.bars field.
>
> - If I just create the field:
>
>   class Foo(models.Model)
>       foo_id = models.IntegerField(primary_key = True)
>       xyz = models.CharField(max_length = 20)
>       bars = []
>
> Then the list belongs to the class, not instances.
>
> - If I try creating the field lazily, e.g.
>
>   class Foo(models.Model)
>       foo_id = models.IntegerField(primary_key = True)
>       xyz = models.CharField(max_length = 20)
>
>       def attach_bar(self, bar):
>           if self.bars is None:
>               self.bars = []
>           self.bars.append(bar)
>
> Then calling attach_bar from the application results in an
> AttributeError, 'Foo' object has no attribute 'bars'.
>
> - Specifying Foo.__init__ to initialize bars doesn't work, because it
> interferes with creation of Foo objects from database queries.
>
> I played around with subclassing, e.g. class FooBase
> (models.Model) ... class Foo(FooBase) but couldn't get that to work.
>
> How can I add a field to the Foo class that doesn't come from the
> database?
>
> Jack Orenstein
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to