如何用ManyToMany字段过滤?

时间:2019-12-11 08:43:37

标签: django django-rest-framework serializer

要约有多种产品。当我尝试打印所选产品的详细信息时,它显示了一些错误

型号

class Products(models.Model):
    name = models.CharField(max_length=30)
    price = models.CharField(max_length=30)


class Offer(models.Model):
    offer = models.IntegerField(default=0)
    products = models.ManyToManyField(Publication)

序列化器

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = ['name', 'price']

class OfferSerializer(serializers.ModelSerializer):
    products_list = serializers.SerializerMethodField()

    class Meta:
        model = Offer
        fields = ['id', 'offer', 'products_list']
        read_only_fields = ['id']

    def get_products_list(self, instance):
            products_id = instance.products
            products = Products.objects.filter(id=products_id)

            return ProductSerializer(products, many=True).data

错误

TypeError: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager'

2 个答案:

答案 0 :(得分:1)

您试图将ManyToManyManager值而不是id传递给过滤器。您可以使用经理的all()方法获得所有产品。

def get_products_list(self, instance):
    products = instance.products.all()  # <- this is the issue
    return ProductSerializer(products, many=True).data

答案 1 :(得分:0)

如果要获取要约的所有产品,只需在OfferSerializer中使用ProductSerializer

class OfferSerializer(serializers.ModelSerializer):
    products_list = ProductSerializer(many=True)

顺便说一句,在SerializerMethodField中查询不是很理想,如果在列表中使用序列化程序,它将多次访问数据库请求,在这种情况下,您应该尝试使用Django Subquery expression