views:

19

answers:

2

Hi,

I have a django.contrib.contenttypes.generic.genericForeignKeyField as a member of my model,

however, it is not appearing when I instantiate the model and then try to get the fields out of the _meta of the object.

e.g:

class A(models.Model):
    field2 = models.IntegerField(...)
    field1 = generic.genericForeignKeyField()

a = A()
a._meta.fields   ---> this does not show field1, but shows field2. 

Can someone please tell me why ?

Thanks !

+1  A: 

Your are not setting up the generic relation correctly. Read the documentation:

There are three parts to setting up a GenericForeignKey:

  1. Give your model a ForeignKey to ContentType.
  2. Give your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.)
    This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key.
  3. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named "content_type" and "object_id", you can omit this -- those are the default field names GenericForeignKey will look for.

In the end, it must be something like:

content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
Felix Kling
+1  A: 

Why would you expect it to? It's not a real field. It's a virtual field that's calculated using the (real) content_type and object_id fields on the model.

You can however see it in a._meta.virtual_fields.

Daniel Roseman