如何解决重命名 ContentTypeFramework 中的 content_type 和 object_id
我想在我的 Django 应用程序中创建特定关系。为此,我选择了 ContentTypeFramework 和 GenericForeignKey。在 django 文档中,关于它的信息并不多。这是:
设置 GenericForeignKey 分为三个部分:
- 为您的模型提供一个 ContentType 的外键。这个的常用名称 字段为“content_type”。
- 为您的模型提供一个字段,该字段可以存储您将要关联的模型的主键值。对于大多数模型,这意味着 PositiveIntegerField。此字段的常用名称是“object_id”。
- 为您的模型提供一个 GenericForeignKey,并将上述两个字段的名称传递给它。如果这些字段被命名为“content_type”和“object_id”,你可以省略它——这些是 GenericForeignKey 将寻找的默认字段名称。
content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
object_id = models.UUIDField(null=True,blank=True)
item = GenericForeignKey('content_type','object_id')
但是如果我改变他们的名字,为了更具体的东西(只是自定义字段名称),例如:
item_ct = models.ForeignKey(ContentType,on_delete=models.CASCADE)
item_id = models.UUIDField(null=True,blank=True)
item = GenericForeignKey('item_ct','item_id')
我的应用程序测试失败并带有回溯:
..................
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py",line 1021,in add_annotation
annotation = annotation.resolve_expression(self,allow_joins=True,reuse=None,File "/usr/local/lib/python3.8/site-packages/django/db/models/expressions.py",line 625,in resolve_expression
c.source_expressions[pos] = arg.resolve_expression(query,allow_joins,reuse,summarize,for_save)
File "/usr/local/lib/python3.8/site-packages/django/db/models/aggregates.py",line 47,in resolve_expression
c = super().resolve_expression(query,summarize)
File "/usr/local/lib/python3.8/site-packages/django/db/models/expressions.py",for_save)
File "/usr/local/lib/python3.8/site-packages/django/db/models/expressions.py",line 532,in resolve_expression
return query.resolve_ref(self.name,simple_col)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py",line 1685,in resolve_ref
join_info = self.setup_joins(field_list,self.get_Meta(),self.get_initial_alias(),can_reuse=reuse)
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py",line 1567,in setup_joins
path,final_field,targets,rest = self.names_to_path(
File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py",line 1496,in names_to_path
pathinfos = field.get_path_info(filtered_relation)
File "/usr/local/lib/python3.8/site-packages/django/contrib/contenttypes/fields.py",line 399,in get_path_info
object_id_field = opts.get_field(self.object_id_field_name)
File "/usr/local/lib/python3.8/site-packages/django/db/models/options.py",line 583,in get_field
raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name,field_name))
django.core.exceptions.FieldDoesNotExist: Record has no field named 'object_id'
那么,有没有人遇到过同样的问题,也许有人知道如何解决它们?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。