我希望将项目添加到django模型中的manytomany字段中。目前正在创建新的标记对象,但是当我在管理员中调用save时,它不会被添加到MyModel
。我的代码没有任何错误,有什么想法吗?
class Tag(models.Model):
text = models.SlugField(max_length=50, unique=True)
class MyModel(models.Model):
tags = models.ManyToManyField("Tag", blank=True)
def save(self, *args, **kwargs):
if (self.tags.count() == 0):
tag, created = Tag.objects.get_or_create(text=get_word())
tag.save()
self.tags.add(tag)
return super(MyModel, self).save(*args, **kwargs)
答案 0 :(得分:0)
首先你需要保存MyModel实例,然后使用self.tags.add(tag)
class MyModel(models.Model):
tags = models.ManyToManyField("Tag", blank=True)
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs) # saving MyModel instance
tag, created = Tag.objects.get_or_create(text=get_word())
tag.save()
self.tags.add(tag) # adding m2m to saved instance MyModel
return self
答案 1 :(得分:0)
为了向ManyToMany字段添加一些值,您可以使用post_save信号
from django.db.models.signals import post_save
from django.dispatch import receiver
class MyModel(models.Model):
tags = models.ManyToManyField("Tag", blank=True)
@receiver(post_save, sender=MyModel)
def update_related_doc_sync(sender, instance, **kwargs):
# get or create Tag - no need to call .save()
tag, created = Tag.objects.get_or_create(text=get_word())
# add tag to M2M field
instance.tags.add(tag)