DJANGO REST框架search_fields viewset从genericForeignkey字段模型



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

模型:

   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:字段"评论员"不会生成自动反向关系,因此不能用于反向查询。如果是通用foreignkey,请考虑添加通用相关。

您需要在每个模型中添加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 s的列表:

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

请参考文档的这一部分,以了解有关GenericRelation

的更多信息。

您需要在每个型号中添加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"]

相关内容

  • 没有找到相关文章

最新更新