如何在 Django 中重复多对多关系?

How to repeat a many-to-many relationship in Django?

我的 Django 应用程序中有这些模型:

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class Animal(models.Model):
    name = models.CharField(max_length=100, unique=True)

class AnimalList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    list = models.ManyToManyField(Amimal)

我想将同一个神奇宝贝添加到同一个列表两次:

>>> animal = Animal.objects.create(name='milla')
>>> user = User.objects.create(username='user')
>>> list = AnimalList.objects.create(user=user)
>>> list.list.add(animal)
>>> list.list.add(animal)
>>> animal.save()

虽然只添加了一次动物:

>>> list.list.all()
<QuerySet [<Animal: Animal object (3)>]>

我预计,the documentation 明确表示

Adding a second time is OK, it will not duplicate the relation:

然而,我确实想重复这些动物。

我该怎么做?是否可以使用 ManyToManyField?

我无法重复这些关系,因为 Django 将 UniqueConstrant 应用于多对多关系。我的解决方案是添加另一个引用动物的 table:

class AnimalListItem(models.Model):
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE)

class AnimalList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    list_items1 = models.ManyToManyField(AnimalListItem)

之后,每次我想将动物添加到列表中时,我都必须先创建一个列表项,指向该动物,然后将此列表项添加到列表列中。

还有其他可能的解决方案。例如,没有 through.

through argument from ManyToManyField disables any default constraints that would be added to the relationship table. Or you could set db_constraint to False

但是,这些都不是我的解决方案,因为 the documentation states:

If the custom through table defined by the intermediate model does not enforce uniqueness on the (model1, model2) pair, allowing multiple values, the remove() call will remove all intermediate model instances

我一次只需要删除一个实例,所以删除所有实例是不可行的。