【问题标题】:I want to use ForeignKey Serializer我想使用 ForeignKey 序列化器
【发布时间】:2021-05-04 20:52:19
【问题描述】:
I have these Models Below


class Campaign(models.Model):
    title = models.CharField(max_length=120)
    img = models.ImageField(upload_to='products/')

    def __str__(self):
        return self.title
class Product(models.Model):
    title = models.CharField(max_length=100)
    data = models.DateField(auto_now_add=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to="products/")
    campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="products")
    offer = models.ForeignKey(Offer, on_delete=models.DO_NOTHING, null=True, blank=True)
    market_price = models.PositiveIntegerField()
    selling_price = models.PositiveIntegerField()
    description = models.TextField()

    def __str__(self):
        return self.title

我想展示campaign_wise 产品。但我找不到任何解决方案。虽然我尝试阅读 DRF 的文档

这是我的序列化器

class CampaignProductsSerializer(serializers.ModelSerializer):
    products = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    class Meta:
        model = Campaign
        fields = ['title', 'products']

Whenever i try to run this i get 'Product' object has no attribute 'products'

这是我的网址

path('campaign_products/<int:id>/', CampaignProducts.as_view()),

这是我的观点:

class CampaignProducts(APIView):
    def get(self, request, id):
        campaigns = Campaign.objects.all()
        query = Product.objects.filter(campaign_id = id)
        serializer = CampaignProductsSerializer(query, many=True)
        return Response(serializer.data)

【问题讨论】:

    标签: python django api django-rest-framework


    【解决方案1】:

    在这种情况下,您应该制作两个序列化程序,一个用于Product,一个用于Campaign,所以:

    class ProductSerializer(serializers.ModelSerializer):
        class Meta:
            model = Product
            fields = ['title']  # etc.
    
    
    class CampaignProductsSerializer(serializers.ModelSerializer):
        products = ProductSerializer(read_only=True, many=True)
    
        class Meta:
            model = Campaign
            fields = ['title', 'products']

    然后在视图中序列化一个Campaign:

    from django.shortcuts import get_object_or_404
    
    # returns the title of the campaign, and the products
    class CampaignProducts(APIView):
        def get(self, request, id):
            campaign = get_object_or_404(Campaign, id=id)
            serializer = CampaignProductsSerializer(campaign)
            return Response(serializer.data)

    如果您不想包含广告系列的数据,我们可以使用ProductSerializer

    # returns only the related products
    class CampaignProducts(APIView):
        
        def get(self, request, id):
            products = Product.objects.filter(campaign_id=id)
            serializer = ProductSerializer(products, many=True)
            return Response({'data': serializer.data})

    【讨论】:

    • 谢谢你救了我的一天
    猜你喜欢
    • 2017-03-25
    • 2022-11-18
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多