通用外键字段模型中的Django Rest Framework search_fields视图集

时间:2019-06-26 16:17:29

标签: django django-rest-framework

所有模型(客户,提供者,联系人,雇员)都具有相同的名称字段,在主模型或通用模型(注释)中具有通用外键。我需要在主模型中搜索字段。就是这样吗?

型号:

   class Customer(TimeStampedModel):
       name = models.CharField()

   class Provider(TimeStampedModel):
       name = models.CharField()

   class Contact(TimeStampedModel):
       name = models.CharField()

   class Employee(TimeStampedModel):
       name = models.CharField()


   class Comment(TimeStampedModel):
       content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
       object_id = models.PositiveIntegerField()
       commentator = GenericForeignKey('content_type', 'object_id')

视图集

class CommentsViewSet(BaseViewSet):
       queryset = Comments.objects.all()
       serializer_class = CommentsSerializer
       search_fields = ["commentator__name",]

消息错误:

  

django.core.exceptions.FieldError:字段“ commentator”不会生成自动反向关系,因此无法用于反向查询。如果它是GenericForeignKey,请考虑添加GenericRelation。

2 个答案:

答案 0 :(得分:0)

您需要add a GenericRelation进入每个模型。

class Customer(TimeStampedModel):
   name = models.CharField()
   comment = GenericRelation(Comment, related_query_name='customer')

class Provider(TimeStampedModel):
   name = models.CharField()
   comment = GenericRelation(Comment, related_query_name='provider')
...

search_fields = ["customer__name", "provider__name", "contact__name", "employee_name"]

答案 1 :(得分:-1)

您需要向每个能够接收注释的模型添加一个GenericRelation字段,例如:

   class Customer(TimeStampedModel):
       name = models.CharField()
       comments = GenericRelation('Comment', related_query_name='customer')

   class Provider(TimeStampedModel):
       name = models.CharField()
       comments = GenericRelation('Comment', related_query_name='provider')

   class Contact(TimeStampedModel):
       name = models.CharField()
       comments = GenericRelation('Comment', related_query_name='contact')

   class Employee(TimeStampedModel):
       name = models.CharField()
       comments = GenericRelation('Comment', related_query_name='employee')

然后您以这种方式将search_fields属性定义为所有related_query_name的列表:

        search_fields = ["customer__name", "provider__name", "contact__name", "employee__name"]

请参阅to this part of the documentation to know more about GenericRelation