Django ManyToManyField

In my model, I have:

class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) 

I am trying to create a Poll object and store tags as follows:

 Tags = [] for splitTag in splitTags: tag = Tag(name = splitTag.lower()) tag.save() Tags.append(tag) 

How to set Tags array and assign it Tags ?

I tried:

  poll = Poll(topic=topic, tags = Tags) poll.save() 
+4
source share
2 answers

Well, it should be something like this:

 models.py class Tag(models.Model): name = models.CharField(max_length=200) class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) in views.py: poll = Poll(topic="My topic") poll.save() for splitTag in splitTags: tag = Tag(name = splitTag.lower()) tag.save() poll.tags.add(tag) poll.save() 
+12
source

I see that you are trying to create your own tag system, but I think this can help if you look at an existing one.

http://code.google.com/p/django-tagging/

I use this in my applications and it has an awesome api for download.

+3
source

Source: https://habr.com/ru/post/1338614/


All Articles