DRF 链式显示的问题,serializer.charField(source=xxx)的使用
两个模型类
class OrderModel(models.Model):
customer = models.ForeignKey(to='customermodel',on_delete=models.DO_NOTHING,related_name='order',null=True,blank=True,db_constraint=False)
class CustomerModel(models.Model):
user = models.ForeignKey(to='login.User',on_delete=models.DO_NOTHING,null=True,blank=True,db_constraint=False,related_name='customer')
序列化器类
正向查询
class OrderSerializer(serializers.ModelSerializer):
# 链式查询,若想让界面显示外联的字段,需要在多的一方的序列化器中,重新定义,source指向,并添加到fields字段
customer = serializers.CharField(source='customer.user')
class Meta:
model = OrderModel
fields = ('order_name','delivery_num','description','is_delivery','customer')
反向查询
class CustomerSerializer(serializers.ModelSerializer):
# 定义的字段必须与releate_name相同
order = OrderSerializer(many=True)
class Meta:
model = CustomerModel
fields = ('name','age','phone','sex','address','user')
class OrderViewSet(ModelViewSet):
# queryset = OrderModel.objects.all()
serializer_class = OrderSerializer
def get_queryset(self):
# queryset = OrderModel.objects.all()
if self.request.user.is_superuser:
queryset = OrderModel.objects.all()
else:
# 链式查询字段名__另一个模型关联字段名__另一个模型的关联字段名 这是一个三级关联查询
queryset = OrderModel.objects.filter(customer__user__username=self.request.user)
return queryset
参考链接
https://blog.csdn.net/weixin_38836909/article/details/112790439
比较全面的参考博客:
https://www.liujiangblog.com/course/django/129