Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to allow for duplicate many-to-many entries in Python/Django

I have the following Django model:

class Icon(models.Model):
    name = models.CharField(max_length=200,null=False,blank=False)

class Post(models.Model):
    icons = models.ManyToManyField(Icon)

When I write the following code:

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()

It works fine for the most part, creating a Post object and the two Icon objects.

However, if the icon_id is, say, 1 in both cases, it only creates ONE entry in the database, not two.

So it seems like it checks for duplicates and removes them.

How do I make this work so I allow duplicates? (I want two of the SAME icon associated with a post.)

Thanks!

like image 210
ryankicks Avatar asked Aug 31 '11 17:08

ryankicks


People also ask

How do you add ManyToMany values in Django?

Now let's see how to add an object to a ManyToManyField in Django. To do so, Django has a built-in function, add(), which allows us to do so. This would be done in the views.py file.

How do I get rid of ManyToMany field data in Django?

ManyToMany field has some methods that you can call: add(Object) remove(Object) clear() this one is for removing all objects.

How does ManyToMany field work in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.


1 Answers

Define the model yourself, to have such non-unique many-to-many relations

class PostIcon(models.Model):
    post = models.ForeignKey(Post)
    icon = models.ForeignKey(Icon)

and than add them one by one

for icon in icons:
    PostIcon(post=post, icon=icon).save()

or pass that model as through argument of ManyToManyField e.g.

class Post(models.Model):
    icons = models.ManyToManyField(Icon, through=PostIcon)

or alternatively you can have a count associated with PostIcon instead of having multiple rows, if that serves the use-case e.g. you may want a badge to be displayed 10 times

class PostIcon(models.Model):
    post = models.ForeignKey(Post)
    icon = models.ForeignKey(Icon)
    count =  models.IntegerField()
like image 112
Anurag Uniyal Avatar answered Oct 30 '22 22:10

Anurag Uniyal