views:

89

answers:

1

I currently have these models:

class Category(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
    description = models.TextField(blank=True,null=True)

class Item(models.Model):
    name = models.CharField(max_length=500)
    ...
    tag = models.ManyToManyField(Category, null=True, blank=True, related_name='tag_item')

My issue is, I can't add tags to any Items that I've already created. If I attempt to do something like:

>>> cat = Category.objects.get(pk=1)
>>> cat.tag_item.create(item_id = 1)

I get TypeError: 'item_id' is an invalid keyword argument for this function

However, if I do:

>>> cat.tag_item.create()

I end up with a newly created empty item.

I also don't understand how I would perform a query to get all tags for a particular item? There is no Tag class because I don't have to specify a through attribute on the ManyToManyField since there is no extra data, so I can't use a Tag manager to do something like Tag.objects.filter(item_id=3)

+2  A: 

Have a look at some examples here.

Basically, you should do:

class Item(models.Model):
    name = models.CharField(max_length=500)
    ...
    tags = models.ManyToManyField(Category, blank=True)

To create an item, a tag and associate them, do the following:

item = Item(name='test')
item.save()
tag = Category(name='foo')
item.tags.add(tag)

and to query all tags:

item.tags.all()
jbochi