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

后端 未结 1 999
野的像风
野的像风 2021-01-19 02:42

I have the following Django model:

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

class Post(models.Model):
           


        
相关标签:
1条回答
  • 2021-01-19 02:51

    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()
    
    0 讨论(0)
提交回复
热议问题