gpt4 book ai didi

python - Django:具有订购和添加/删除关系能力的 ManyToMany?

转载 作者:行者123 更新时间:2023-11-28 22:55:51 25 4
gpt4 key购买 nike

我正在构建一个网络应用程序,它允许用户拥有一个照片库,里面装满了照片对象,他们可以将这些照片对象放入相册中。他们可以执行以下操作:

  • 将照片添加到相册
  • 从相册中删除照片
  • 更改相册中照片的顺序
  • 将同一张照片放入多个相册
  • 将一张照片多次放入相册

最初,我曾想像这样(简化)编写模型:

def Photo(models.Model):
user = models.ForeignKey(User)
img_file = models.ImageField(upload_to = img_get_file_path)
upload_date = models.DateTimeField(auto_now_add = True)


def Album(models.Model):
title = models.CharField(max_length = 50, required = False)
cover_img = models.ForeignKey(Photo)
album_contents = models.ManyToMany(Photo)

# a user's "photo library" isn't defined in a model, but
# rather by running the query:
# Photo.objects.filter(user = request.user).order_by('upload_date')

这种简单的方法本来会很有效,但用户无法更改其相册中照片的顺序(ManyToMany relationships 未排序)。我已经搜索了解决方案,每个人都指向使用 intermediate models ,使用 through 语句:

中间模型方法适用于对相册中的照片进行排序,但不适用于从相册中删除照片。 Intermediate models不支持 .add().create().remove() 或赋值。它们只支持.clear() 方法,该方法会清除整个相册。我需要用户能够一次从相册中删除一张照片,同时仍然能够对相册中的照片进行排序。

我怎样才能做到这一点?

最佳答案

你不应该让 django 删除添加、创建、删除的事实阻止你做任何事情。

仅仅因为它“仅”支持 .clear() 方法,并不意味着您不能编写普通的 python 代码来替换该功能。

The intermediate model approach would work in ordering the photos in the album, but not in removing photos from an album. Intermediate models don't support .add(), .create(), .remove(), or assignment. They only support the .clear() method, which would clear the entire album. I need users to be able to remove one photo from an album at a time, while still being able to order the photos in the album.

我不明白是什么阻止您删除一种关系而不是所有关系。

只要找到M2M中间表的实例,删除行即可。这是一个普通的 django 模型。

# say you have a photo that the user wants to remove from album.
album = Album.objects.latest('id')
photo = Photo.objects.album_contents.latest('id')

# to remove that m2m relationship...
# delete the through table row which matches said relationship
MyThroughTable.objects.filter(album=album, photo=photo).delete()

关于python - Django:具有订购和添加/删除关系能力的 ManyToMany?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16290559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com