Order many-to-many field by the order values were inserted
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Order many-to-many field by the order values were inserted on this date .
# models.py from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to=avatar_photo_upload, blank=True) banner = models.ImageField(upload_to=banner_photo_upload, blank=True) bio = models.TextField(max_length=150, blank=True) date_joined = models.DateField(auto_now_add=True) time_joined = models.TimeField(auto_now_add=True) def __str__(self) -> str: return self.user.username class Friend(models.Model): # The friends, sender first, reciever second friends = models.ManyToManyField(Profile) # accepted or rejected accepted = models.BooleanField(default=False) rejected = models.BooleanField(default=False) date_added = models.DateField(auto_now=True) time_added = models.TimeField(auto_now=True) def __str__(self): if self.accepted == False and self.rejected == False: return f'{" sent a request to ".join([i.user.username for i in self.friends.all()])}' else: if self.accepted == True and self.rejected == True: return f'{" was a friend of ".join([i.user.username for i in self.friends.all()])}' elif self.accepted == True and self.rejected == False: return f'{" is a friend of ".join([i.user.username for i in self.friends.all()])}' else: return f'{" was rejected as a friend by ".join([i.user.username for i in self.friends.all()])}'
The friends
field is a many-to-many field
,
Understanding my problem with an example:
for example -> Profile object a
is created, and then Profile object b
.
Now I add profile object b
in the friend
field and then object a
, but the friend
field orders them in a
then b
…
How do order them by time added.
Thank you.
EDIT:
Expected output: The same order in which the values were inserted.
Answer
Django Many To Many Insert Ordering
Django doesn’t guarantee to preserve the order of many-to-many relationships. If you need this, you should use a through table with an explicit ‘order’ field.