开发者

django/taggit - error: MyData objects need to have a primary key value before you can access their tags

开发者 https://www.devze.com 2023-02-22 05:40 出处:网络
I\'m trying to use django-taggit (see). This is what I have in my code: models.py class MyData(models.Model):

I'm trying to use django-taggit (see). This is what I have in my code:

models.py

class MyData(models.Model):
    title = models.CharField(blank=True, max_length=50)
    .....
    tags = TaggableManager()

views.py

g = MyData(title=f_title)   
g.tags.add( "mytag" )
g.save()

For some reason when I'm trying to save the tags and the data I'm getting this error:

MyData objects need to have a primary key value before you can acces开发者_如何学运维s their tags.

Any ideas? Thank you!


use MyData.objects.create(title=f_title) for it to be saved to the DB and have an Id then access tags

g = MyData.objects.create(title=f_title)  
g.tags.add( "mytag" )
g.save()


Change the order. Save first -- which assigns a primary key -- then mess with the tags.


As the error says, your MyData object must have a primary key before you add tags. This is because the tags are stored via a many to many relationship, and you need the ID so you can link it in a separate table. Simple solution is to do:

g = MyData(title=f_title)   
g.save()
g.tags.add( "mytag" )
g.save()
0

精彩评论

暂无评论...
验证码 换一张
取 消