的更多信息。
所有模型(客户,提供者,联系人,员工(具有相同的名称字段,可以在主模型或通用模型(注释(中具有通用的外键。我需要在主模型中搜索字段。就是这样?
模型:
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"]