generic relation setting content_object with unsaved model

829 views Asked by At

Say I have the following model:

class Foo(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

class Bar(models.Model):
    baz = models.BooleanField()

then run the following code:

f = Foo(content_object=Bar(baz=False))
print f.content_object

what I would expect to see is something like:

<Bar: Bar object>

but instead it seems as if it's empty... why is this?

2

There are 2 answers

1
Tomasz Zieliński On BEST ANSWER

Content_object has to be split into content_type and object_id. And until you save the object into the database there is no object_id available. Therefore you have to save it first - like Sandip suggested. You can do it in a shorter form as well: Baz.objects.create(baz=False)

0
Sandip Agarwal On

Follow the following:

b=Bar(baz=False)
b.save()
f = Foo(content_object=b)
f.content_object

This gives the desired result for you.