如何表示djangorestgrameworks序列化程序类中的所有ManyToMany字段



我想使用django呈现具有这些值的ManyToMany字段。

基本型号

class SalesAction(models.Model):
sales_representative = models.ForeignKey(
SalesRepresentative, on_delete=models.CASCADE)
doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
remark = models.CharField(max_length=500)
date = models.DateField()
medicines = models.ManyToManyField(Medicine, through='SalesActionMedicine')
def __str__(self):
return f'{self.sales_representative} - {self.doctor}'

详细型号

class SalesActionMedicine(models.Model):
sales_action = models.ForeignKey(SalesAction, on_delete=models.CASCADE)
medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE)
quantity_type = models.CharField(max_length=50)
quantity = models.PositiveIntegerField()

我想要的是表示与SalesAction模型类中的每个对象相关的所有药物。

这是我构建的序列化程序。

class SalesActionMedicineSerializer(serializers.ModelSerializer):
class Meta:
model = SalesActionMedicine
fields = ('sales_action', 'medicine', 'quantity_type', 'quantity')
class SalesActionSerializer(serializers.ModelSerializer):
medicines = SalesActionMedicineSerializer(many=True)
class Meta:
model = SalesAction
fields = ('sales_representative', 'doctor', 'remark', 'date', 'medicines')

这个代码给了我这个错误:

Got AttributeError when attempting to get a value for fieldsales_actionon serializersales_action MedicineSerizer. The serializer field might be named incorrectly and not match any attribute or key on theMedicineinstance. Original exception text was: 'Medicine' object has no attribute 'sales_action'.

您需要使用MedicineSerializer而不是SalesActionMedicineSerializer来获取药物。您也可以使用reverse获取SaleActionMedicine数据。

所以,代码将是

class SalesActionSerializer(serializers.ModelSerializer):
medicines = MedicineSerializer(many=True)
sales_medicines = SalesActionMedicineSerializer(source='salesactionmedicine_set', many=True)
class Meta:
model = SalesAction
fields = ('sales_representative', 'doctor', 'remark', 'date', 
'medicines', 'sales_medicines')

最新更新