允许在Python/Django中重复的多对多条目的方法
我有一个Django模型,如下所示:
class Icon(models.Model):
name = models.CharField(max_length=200,null=False,blank=False)
class Post(models.Model):
icons = models.ManyToManyField(Icon)
当我写下以下代码时:
post = Post()
icons = []
icon_id = form.cleaned_data['icon_1']
if (icon_id):
i = Icon.objects.get(id=icon_id)
icons.append(i)
icon_id = form.cleaned_data['icon_2']
if (icon_id):
i = Icon.objects.get(id=icon_id)
icons.append(i)
post.icons = icons
post.save()
大部分情况下,这段代码运行得很好,它创建了一个Post对象和两个Icon对象。
不过,如果两个icon_id都是1的话,它只会在数据库里创建一个记录,而不是两个。
看起来它会检查重复项,并把重复的去掉。
我该怎么做才能允许重复呢?(我想让一个帖子关联两个相同的图标。)
谢谢!
1 个回答
14
自己定义模型,这样就可以有很多对多的关系,而且这些关系可以不是唯一的。
class PostIcon(models.Model):
post = models.ForeignKey(Post)
icon = models.ForeignKey(Icon)
然后一个一个地添加它们。
for icon in icons:
PostIcon(post=post, icon=icon).save()
或者把这个模型作为 ManyToManyField
的 through
参数传入,比如:
class Post(models.Model):
icons = models.ManyToManyField(Icon, through=PostIcon)
另外,你也可以给 PostIcon
关联一个计数,而不是创建多行数据,这样可以满足你的需求,比如你可能想让一个徽章显示10次。
class PostIcon(models.Model):
post = models.ForeignKey(Post)
icon = models.ForeignKey(Icon)
count = models.IntegerField()