Pergunta

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?

Foi útil?

Solução

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)

Outras dicas

Follow the following:

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

This gives the desired result for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top