Django通用关系字段报告,当没有ARGS传递时,所有()都将获得意外的关键字参数

StackOverflow https://stackoverflow.com/questions/2688691

  •  30-09-2019
  •  | 
  •  

我有一个模型,可以附加到其他模型上。

class Attachable(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_pk = models.TextField()
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")

    class Meta:
        abstract = True

class Flag(Attachable):
    user = models.ForeignKey(User)
    flag = models.SlugField()
    timestamp = models.DateTimeField()

我在另一个模型中与此模型建立了通用关系。

flags = generic.GenericRelation(Flag)

我尝试从这种通用关系中获取对象:

self.flags.all()

这导致以下例外:

>>> obj.flags.all()        
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all
    return self.get_query_set()                                                              
  File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set
    return superclass.get_query_set(self).filter(**query)                                                         
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter                    
    return self._filter_or_exclude(False, *args, **kwargs)                                                        
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude        
    clone.query.add_q(Q(*args, **kwargs))                                                                         
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q                
    can_reuse=used_aliases)                                                                                       
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter           
    negate=negate, process_extras=process_extras)                                                                 
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins          
    "Choices are: %s" % (name, ", ".join(names)))                                                                 
FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user
>>> obj.flags.all(object_pk=obj.pk)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: all() got an unexpected keyword argument 'object_pk'

我做错了什么?

有帮助吗?

解决方案

您需要定义 object_id_fieldcontent_type_field 创建时 GenericRelation:

flags = generic.GenericRelation(Flag, object_id_field="object_pk", content_type_field="content_type")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top