generic relation setting content_object with unsaved model
-
19-04-2021 - |
Question
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?
Solution
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)
OTHER TIPS
Follow the following:
b=Bar(baz=False)
b.save()
f = Foo(content_object=b)
f.content_object
This gives the desired result for you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow