我有一个序列化程序,它的值来自OneToMany
和ManyToOne
关系。你知道吗
class A(models.Model):
abc = AnyField()
bcd = AnfField()
class B(models.Model):
xyz = ForeignKey(A)
pqr = CharField()
class C(models.Model):
lmn = ForeignKey(A)
def = CharField()
我的序列化程序如下所示:
class BSerializer(ModelSerializer):
class Meta:
fields = '__all__'
class CSerializer(ModelSerializer):
class Meta:
fields = '__all__'
class ASerializer(ModelSerializer):
B = SerializerMethodField()
C = SerializerMethodField()
class Meta:
fields = ('id', 'abc', 'bcd', 'B', 'C')
def get_B(self, obj):
return BSerializer(queryset=obj.b_set.all(), many=True).data
def get_C(self, obj):
return CSerializer(queryset=obj.c_set.all(), many=True).data
在我看来:
class AListView(ListAPIView):
serializer_class = ASerializer
queryset = A.objects.all()
search_fields = ('id', 'abc', 'bcd', 'B__pqr', 'C__def', )
我想在序列化程序字段中搜索。
有没有一种方法,我可以在B
的字段或'C'的字段中搜索。你知道吗
使用search_fields
,我只能搜索A
的字段(abc
,bcd
)。你知道吗
为了搜索“B_u-pqr”和“C_u-def”,模型应该与B和C模型保持一元关系。或者需要在模型中保持B和C模型的外键关系。我想说的。你知道吗
这样,您就可以从模型中搜索B或C的属性。你知道吗
编辑响应:
另一种可能的解决方案是覆盖列表并返回预期的响应。但我必须提到这是一种黑客的解决方案。你知道吗
相关问题 更多 >
编程相关推荐