多对多的保存方法
我有一个叫做Card的模型,它和Tag之间有多对多的关系。每当我保存一个Card的时候,我也想创建一个Product,并且这个Product也要和Tag有相同的多对多关系。
我该如何获取这个实例的标签呢?使用self.tags.all()
时返回的是一个空列表,但如果我在保存后检查,发现Card实际上是有标签的。我的代码如下。顺便说一下,我使用的是Django 1.0.5。
class Card(models.Model):
product = models.ForeignKey(Product, editable=False, null=True)
name = models.CharField('name', max_length=50, unique=True, help_text='A short and unique name or title of the object.')
identifier = models.SlugField('identifier', unique=True, help_text='A unique identifier constructed from the name of the object. Only change this if you know what it does.', db_index=True)
tags = models.ManyToManyField(Tag, verbose_name='tags', db_index=True)
price = models.DecimalField('price', max_digits=15, decimal_places=2, db_index=True)
def add_product(self):
product = Product(
name = self.name,
identifier = self.identifier,
price = self.price
)
product.save()
return product
def save(self, *args, **kwargs):
# Step 1: Create product
if not self.id:
self.product = self.add_product()
# Step 2: Create Card
super(Card, self).save(*args, **kwargs)
# Step 3: Copy cards many to many to product
# How do I do this?
print self.tags.all() # gives an empty list??
2 个回答
0
你没有给卡片添加任何标签。在你保存卡片之前,是不能添加多对多关系的。而在调用 save
方法和 self.tags.all()
之间,没有时间去设置这些标签。
2
你是在用django-admin来保存模型和标签吗?很多对多的字段在模型保存后才会被保存。这时候你可以重写admin类的save_model方法。比如:
class CardAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.save()
form.save_m2m()
#from this point on the tags are accessible
print obj.tags.all()