Django restframework排序

fnx2tebb  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(150)

models.py

class Entity(BaseFields):
    entity_name_en = models.CharField(max_length=250)
    category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True,blank=True)
class EntityRelation(models.Model):
    name = models.CharField(max_length=250)

class EntityRelationship(models.Model):
    entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="entity")
    relation = models.ForeignKey(EntityRelation,on_delete=models.CASCADE)
    related_entity = models.ForeignKey(Entity, on_delete=models.CASCADE, related_name="related_entity")

AlternityRelation包含“Parent”和“Child”

serializers.py

class EntityListserializer(ModelSerializer):
    parent = SerializerMethodField(read_only=True)

   def get_parent(self, obj):
       relation_obj = EntityRelationship.objects.filter(entity=obj,relation__name="Parent").first()
        if relation_obj:
            return {"id":relation_obj.id,"related_entity":{"id":relation_obj.related_entity.id,"name":relation_obj.related_entity.entity_name_en}}
    class Meta:
        model = Entity
        fields = ("id","category","parent")

views.py

class EnityListView(ListAPIView):

    permission_classes = [AllowAny,]
    serializer_class = EntityListserializer

    def get_queryset(self, *args, **kwargs):
        sort = json.loads(self.request.GET.get("sort"))
        parnt = sort.get("parent")
        queryset_list = Entity.objects.all().order_by("-created_date")
    
        if parnt:
            if parnt == 'asc':
                queryset_list = queryset_list.order_by(F("related_entity").asc(nulls_last=True))
            if parnt == 'desc':
                queryset_list = queryset_list.order_by("-related_entity")
        return queryset_list

有谁知道如何用parent字段对queryset_list进行排序
{“id”:1,“category”:1,“parent”:{“id”:1,“related_entity”:{“id”:1,“name”:“实体1”}}

7tofc5zh

7tofc5zh1#

你可能想按entity_name_en排序,在这种情况下,它是:

class EnityListView(ListAPIView):
    permission_classes = [
        AllowAny,
    ]
    serializer_class = EntityListserializer

    def get_queryset(self, *args, **kwargs):
        sort = json.loads(self.request.GET.get('sort'))
        parnt = sort.get('parent')
        queryset_list = Entity.objects.order_by('-created_date')

        if parnt:
            if parnt == 'asc':
                queryset_list = queryset_list.order_by(
                    F('related_entity__entity_name_en').asc(nulls_last=True)
                )
            elif parnt == 'desc':
                queryset_list = queryset_list.order_by(
                    F('related_entity__entity_name_en').desc(nulls_last=True)
                )
        return queryset_list

相关问题