开发者

Django models.Model class member not appearing in model_instance._meta.fields

开发者 https://www.devze.com 2023-01-04 14:41 出处:网络
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开发者_JAVA百科 to get the fields o

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开发者_JAVA百科 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 !


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')


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消