使用Extra字段序列化多对多关系

时间:2018-06-05 13:42:01

标签: django serialization django-rest-framework

请不要试图解决这个问题。猜猜看到其他类似的问题之后我还没有得到什么。

我有这些模特:

class Dish(BaseModel):
    class Meta:
        verbose_name_plural = 'dishes'
    name = models.CharField(_('dish'), max_length=100)
    dish_type = models.CharField(_("dish type"), max_length=100)
    price = models.PositiveIntegerField(_("price"))

    def __str__(self):
        return f"{self.name} costs {self.price}"


class Order(BaseModel):

    dishes = models.ManyToManyField(Dish, through='DishOrder')
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    discount = models.PositiveIntegerField(_("total discount"), blank=True)
    total = models.PositiveIntegerField(_("total"), blank=True)
    shipping = models.PositiveIntegerField(_("shipping cost"), blank=True)
    grand_total = models.PositiveIntegerField(_("grand total"), blank=True)
    country = models.CharField(_('country code'), max_length=2)

    def __str__(self):
        return f"order from {self.customer} at {self.total}"

    def get_absolute_url(self):
        return reverse('order-details', kwargs={'pk': self.pk})


class DishOrder(models.Model):
    dish = models.ForeignKey(Dish, on_delete=models.CASCADE, related_name='dishes')
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='dishes')
    quantity = models.PositiveIntegerField(_("quantity"))
    discount = models.PositiveIntegerField(_("discount"))
    price = models.PositiveIntegerField(_('price'))

相应的序列化器如下:

class DishOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = DishOrder
        fields = (
            "quantity",
            "discount",
            "price"
        )

class OrderSerializer(serializers.ModelSerializer):
    dishes = DishOrderSerializer(source='dish', many=True)
    class Meta:
        model = Order
        fields = (
            "id",
            "country",
            "customer",
            "dishes", 
            "total", 
            "discount",
            "grand_total",
            "voucher"
        )

从可以看出,我通过直通表有一个m2m的关系。但是我无法让序列化器工作。这是我不断得到的错误:

  

尝试获取字段dishes的值时出现AttributeError   在序列化程序OrderSerializer上。序列化程序字段可能已命名   错误且不匹配Order上的任何属性或键   实例。原始异常文本是:'Order'对象没有属性   '盘'。

我一直在仔细研究这个问题,试图找出错误是什么。我将不胜感激任何帮助

1 个答案:

答案 0 :(得分:2)

由于您在模型中使用related_name='dishes',因此您应该使用dishes作为manytomany对象的来源:

class OrderSerializer(serializers.ModelSerializer):
    dishes = DishOrderSerializer(source='dishes', many=True)

或简单:

class OrderSerializer(serializers.ModelSerializer):
    dishes = DishOrderSerializer(many=True)

由于source='dishes'多余,以防您将序列化程序的字段dishes命名为。