LB.
LB.

Reputation: 14122

Django ManyToManyField

In my model I have:

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

I'm trying to create the Poll object and store tags like so:

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

How do I set the Tags array and assign it to tags?

I have tried:

    poll = Poll(topic=topic, tags = Tags)
    poll.save()

Upvotes: 4

Views: 7170

Answers (2)

jbcurtin
jbcurtin

Reputation: 1813

I see that you're trying to build your own tag system, but I think it might help if you take a look at an already existing one.

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

I use that in my apps and it has an awesome api to boot.

Upvotes: 3

Uku Loskit
Uku Loskit

Reputation: 42050

Well, it should be more 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()

Upvotes: 12

Related Questions