Django公司模型。模型类成员未出现在模型\实例中_元字段

2024-09-30 14:30:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django.contrib.contenttypes.generic.genericForeignKeyField作为我模特的一员

但是,当我实例化模型,然后尝试从对象的元中获取字段时,它不会出现。在

例如:

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

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

有人能告诉我为什么吗?在

谢谢!在


Tags: 对象django实例模型modelmodelscontribgeneric
2条回答

你为什么期望它呢?这不是一个真正的领域。它是一个虚拟字段,使用模型上的(real)content_typeobject_id字段进行计算。在

但是您可以在a._meta.virtual_fields中看到它。在

您没有正确设置泛型关系。阅读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.

最后,它一定是这样的:

content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')

相关问题 更多 >