gpt4 book ai didi

python - Django models.Model 类成员未出现在 model_instance._meta.fields 中

转载 作者:行者123 更新时间:2023-12-01 06:16:30 25 4
gpt4 key购买 nike

我有一个 django.contrib.contenttypes.generic.genericForeignKeyField 作为我的模型的成员,

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

例如:

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

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

有人可以告诉我为什么吗?

谢谢!

最佳答案

您没有正确设置通用关系。阅读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')

关于python - Django models.Model 类成员未出现在 model_instance._meta.fields 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3096040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com