Reputation: 5290
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?
Upvotes: 1
Views: 832
Reputation: 16367
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)
Upvotes: 1
Reputation: 1910
Follow the following:
b=Bar(baz=False)
b.save()
f = Foo(content_object=b)
f.content_object
This gives the desired result for you.
Upvotes: 2