ManyToMany 관계가있는 Card라는 모델이 태그에 있습니다. 카드를 저장할 때 나는 태그와 동일한 ManyToMany 관계를 갖고 싶은 Product도 만들고 싶습니다.Save 메서드 manytomany
인스턴스의 태그는 어떻게 액세스합니까? self.tags.all()
은 빈 목록을 제공하고 저장 후 확인하면 카드에 실제로 태그가 있습니다. 내 코드는 다음과 같습니다. 기록을 위해 장고 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??