简体   繁体   English

Django rest 框架组由

[英]Django rest framework group by

I want to group by my data on the basis of ingredient_id so that it does not repeat in response, as you can see am querying on the basis of ingredient_id which is a foreign key so it can be repeated in the database.我想根据成分 ID 对我的数据进行分组,这样它就不会在响应中重复,正如您所见,我正在根据成分 ID 进行查询,这是一个外键,因此可以在数据库中重复。 But I want all the ingredient data to be once and then the supply_chain information around it.但我希望所有成分数据都是一次,然后是它周围的供应链信息。

model.py model.py

class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE)
    stop_name = models.CharField(max_length=1024, null=True, blank=True)
    stop_longitude = models.CharField(max_length=500, null=True, blank=True)
    stop_latitude = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return f'{self.stop_name}'

query询问

@api_view(['GET'])
def supply_chain_response_detail(request, id):
    ingredient_detail = SupplyChainStops.objects.filter(ingredient_id=id).all()
    serializer = SupplyChainStopsSerializer(ingredient_detail, many=True)
    return Response(serializer.data)

Serializer串行器

class IngredientSerializer(serializers.ModelSerializer):
    ingredient_category = IngredientCategorySerializer()
    supplier = SuppliersSerializer()
    origin = OriginSerializer()
    allergies = AllergiesSerializer(many=True)

    class Meta:
        model = Ingredients
        fields = '__all__'


class SupplyChainStopsSerializer(serializers.ModelSerializer):
    ingredient = IngredientSerializer(many=False)

    class Meta:
        model = SupplyChainStops
        fields = '__all__'

You can make a distinct query with a positional argument.您可以使用位置参数进行不同的查询。 Here is a new version of your view.这是您的观点的新版本。

@api_view(['GET'])
def supply_chain_response_detail(request, id):
    ingredient_detail = SupplyChainStops.objects.filter(ingredient_id=id).distinct(
                                               "ingredient_id")
    serializer = SupplyChainStopsSerializer(ingredient_detail, many=True)
    return Response(serializer.data)

NOTE: Positional argument is only supported in PostgreSQL注意:位置参数仅在 PostgreSQL 中受支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM