如何将“ prefetch_related”数据集成到查询集和序列化器中?

时间:2019-04-29 14:05:00

标签: json django serialization django-rest-framework

Hello stackoverflow社区,

我有两个模型,其中包含有关Phones的随机数据。查询集将每部手机的最低价格值发送到我的API ...

models.py

class Phone(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=400)
    image = models.ImageField(upload_to='phone_img/', max_length=255, null=True, blank=True )
    slug_phone = models.SlugField(blank=True)

   <...>

class Price(models.Model):
    price = models.DecimalField(max_digits=6, decimal_places=2)
    date = models.DateField(null=True, blank=True) 
    phone = models.ForeignKey(Phone, on_delete=models.CASCADE)
    market = models.ForeignKey(Market, on_delete=models.CASCADE)

views.py

class PhoneAPI(generics.ListAPIView):
    queryset = Phone.objects.annotate(min_price=Min('price__price'))
    serializer_class = PhoneSerializer

serializers.py

class PhoneSerializer(serializers.ModelSerializer):
    min_price = serializers.IntegerField()

    class Meta:
        model = Phone
        fields = '__all__'

直到这里一切正常,我得到每部手机的最低价格 我的数据库用我的API表示。

API输出

{"count":7,"next":null,"previous":null,"results":[{"id":10,"min_price":718,"name":"SAMSUNG Galaxy S10","description":"SAMSUNG Galaxy S10, Smartphone, 128 GB, Prism Black, Dual SIM","image":"http://127.0.0.1:8000/media/phone_img/galaxy_s10.jpg","slug_phone":"samsung-galaxy-s10"}, <...and so on...>



  

我的问题是,如何访问与之相关的对象与   每个电话的最低价格?例如,价格为   电话。   
  
  因此,我阅读了有关“ prefetch_related”的内容,并尝试在我的视图/查询集中进行。   
  

views.py

class PhoneAPI(generics.ListAPIView):
    queryset = Phone.objects.prefetch_related('price_set').annotate(min_price=Min('price__price'))
    serializer_class = PhoneSerializer

到目前为止,我的API尚未中断,但我也未显示任何相关数据。我需要在serializers.py中指定一个字段来表示数据吗?



更新

正如dirkgroten所说,我将 PriceSerializer 嵌套在 PhoneSerializer 中:

serializers.py

class PhoneSerializer(serializers.ModelSerializer):
    min_price = serializers.IntegerField()
    sdata = PriceSerializer(many=True, read_only=True)

    class Meta:
        model = Phone
        fields = '__all__'

class PriceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Price
        fields = ('id', 'phone', 'price', 'date', 'market')


    phone = serializers.StringRelatedField()
    market = serializers.StringRelatedField()

输出与上面相同,没有新值。

API输出

{"count":7,"next":null,"previous":null,"results":[{"id":10,"min_price":718,"name":"SAMSUNG Galaxy S10","description":"SAMSUNG Galaxy S10, Smartphone, 128 GB, Prism Black, Dual SIM","image":"http://127.0.0.1:8000/media/phone_img/galaxy_s10.jpg","slug_phone":"samsung-galaxy-s10"}, <...and so on..>

0 个答案:

没有答案