Home > Back-end >  Make the number of rows after narrowing-down
Make the number of rows after narrowing-down

Time:07-21

This is my serializer.

class MixSerializer(serializers.ModelSerializer):
    pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p")
    new_order = #I want to get the number order
    class Meta:
        model = Mix
        fields = ('id','pub_date','detail','user','u_key') 

And I narrowing-down the rows like this below.

def get_queryset(self):
    queryset = Mix.objects.all()
    u_key =  self.request.query_params.get('u_key')
    if u_key is not None:
        queryset = queryset.filter(u_key=u_key)
    return queryset

For example, it returns the 30 items from 100 items.

so id should be (1,4,5,6,9,11,13...) like this,

However I want to get the number new_order (1,2,3,4,5,6,....)

I guess I should do some trick in Serializer?

or any other way ?

Any help appreciated.

CodePudding user response:

Well ID is the actual ID in the database, which you don't want to change or override in your queryset (or elsewhere such as your template) because then you would be referring to a different model object, which will cause you problems.

If you want to use ID as some sort of ranking then you have some options, referencing my answer here

The easiest way is to use the forloop.counter in a template or enumerate in a view:

# template
{% for object in objects %}
    # rank is {{ forloop0.counter }}
{% endfor %}
# views
for index, value in enumerate(queryset):
    # order is the index variable
    ...

If you want to explicitly add the rank to the queryset then you can use annotation:

from django.db.models import Window, F
from django.db.models.functions import DenseRank

queryset = Mix.objects.annotate(
    ranking=Window(
        expression=DenseRank(),
        order_by=[
            F('id').desc(),
        ])) 

CodePudding user response:

If you want to get Order Table data, you have to create an Order Serializer and link to this MixSerilizer, Like this,

class OrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = Order
        fields = ('id',)

class MixSerializer(serializers.ModelSerializer):
        pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p")
        new_order = OrderSerializer()

        class Meta:
             model = Mix
             fields = ('id','pub_date','detail','user','u_key','new_order')

models.py

class Mix(models.Model):
      ----
      ----
      order = models.ForeignKey(Order, related_name=new_order, on_delete=models.CASCADE)

If want to get parent table data into a child table you have to pass "related_name" attribute in a models fields. and also that name in a child table sterilizer.

  • Related