Sorting Many to Many relationship in django doesn't work

25 Views Asked by At

I've been trying to implement a sorting solution for so long and nothing has worked so far. I have a Email list and email model. There is a many to many relationship between them. Here's my model and serializer.

Model.py

from django.db import models
from django_extensions.db.models import TimeStampedModel

from users.models import User


class Email(models.Model):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)

    def __str__(self):
        return self.email


class EmailList(TimeStampedModel):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    emails = models.ManyToManyField(Email, related_name='email_lists')

    def __str__(self):
        return self.user.username

Serializers.py

class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Email
        fields = ('email', 'first_name', 'last_name',)



class EmailListRetrieveSerializer(serializers.ModelSerializer):
    emails = EmailSerializer(many=True)

    class Meta:
        model = EmailList
        fields = ('emails', 'id')

I tried to use OrderingFilter but it didn't work. I tried annotation. Same result. I used ChatGPT to come up with a solution he also couldn't give me the solution. Same solution would work on one to many relationship but not on many to many. Please help me figure out a view for this. Thanks a lot.

0

There are 0 best solutions below