django-taggit 从表单中获取标签字符串

django-taggit obtain tags string from form

我尝试使用 django-taggit 作为标签模型。

model.py

class Product(models.Model):
    product_no = models.IntegerField(primary_key=True)
    ... 
    tags = TaggableManager(blank=True)

views.py

def action(request):
    product = Product()

    user = User.objects.get(id=request.user.id)
    product.seller_username = user
    ...

    product.save()

    tag_list = taggit.utils._parse_tags(request.POST['tags'])
    product.tags.add(*tag_list)

当我调用方法 product.tags.add() 时,出现错误

Product objects need to have a primary key value before you can access their tags

我找到的许多解决方案都告诉我在 product.tags.add() 之前放置 product.save() 以使 pk 在访问多对多字段之前可用。 试过了还是报错

注意:save() 方法正常工作。它在产品列表中创建新对象,可以在管理界面中看到。

看来我得改了

product_no = models.IntegerField(primary_key=True)

product_no = models.AutoField(primary_key=True)

已经修复了。