python - Django:ManyToMany 能够排序并添加/删除关系?

标签 python django django-models many-to-many

我正在构建一个 Web 应用程序,允许用户拥有一个照片库,其中充满照片对象,他们可以将其放入相册中。他们可以执行以下操作:

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

最初,我曾想过将模型写成这样(简化):

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 删除 add、create、remove 的事实阻止你做任何事情。

仅仅因为它“仅”支持 .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/

相关文章:

python - 如何在 Django 单元测试中获取请求对象?

python - django:根据对象计数计算百分比

postgresql - 如何在 Django ModelFORM 中获取 UUID FIELD 值?

python - Django/DjangoRestFramework - unittest 未验证使用 ORM 创建的用户

python - 在 django-rest-framework-jwt 中存储超过默认信息

python - Django 模块未找到错误,但它已被删除并删除所有引用

django - 在 Django 中处理 JSON 的最佳方式

django - 收到错误<Follower : Follower object (None)> instance isn't saved. 使用bulk=False 或先保存对象

python - 使 matplotlib 时间序列 'spaghetti' 图中的线条变粗

python - 如何在 python 中扩展 1D FFT 代码来计算图像(2D)的 FFT?