django 按顺序插入多对多字段值

kmbjn2e3  于 2023-01-31  发布在  Go
关注(0)|答案(2)|浏览(145)
# 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 ...
如何按添加的时间订购它们。
谢谢你。

    • 编辑:**

预期产出:与插入值的顺序相同。

yptwkmov

yptwkmov1#

Django Many To Many Insert Ordering
Django不能保证保持多对多关系的顺序,如果你需要,你应该使用一个带有显式'order'字段的直通表。

ymzxtsji

ymzxtsji2#

你可以尝试用创建的id来排序Django ManyToMany字段。

注意:关系数据库创建单独的表。

posts = user.posts.through.objects.all().order_by('-id') #In here user is a model. and posts is ManyToMany field. 
post_list = []
for post in posts:
    get_post = Post.objects.get(id=post.post_id) #Using through only return object id. So use for loop to get the object if required.
    post_list.append(get_post)
return post_list

相关问题