# 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()])}'
friends
字段是many-to-many field
,通过一个示例来理解我的问题:
例如-〉创建了配置文件对象a
,然后创建了配置文件对象b
。现在我在friend
字段中添加了配置文件对象b
,然后添加了对象a
,但是friend
字段将它们排序为a
,然后是b
...
如何按添加的时间订购它们。
谢谢你。
- 编辑:**
预期产出:与插入值的顺序相同。
2条答案
按热度按时间yptwkmov1#
Django Many To Many Insert Ordering
Django不能保证保持多对多关系的顺序,如果你需要,你应该使用一个带有显式'order'字段的直通表。
ymzxtsji2#
你可以尝试用创建的id来排序Django ManyToMany字段。
注意:关系数据库创建单独的表。