2010-01-21 50 views
1

我有一個名爲Card的模型,它與 Tag有ManyToMany關係。當我保存一張卡片時,我想創建一個產品,我希望它具有與標籤相同的ManyToMany關係。保存方法manytomany

如何訪問實例的標籤? self.tags.all()給出了一個空的 列表,如果我在保存後檢查,卡實際上有標籤。我的 代碼如下。爲了記錄,我使用的是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?? 

回答

0

您沒有爲卡片添加任何標籤。在保存卡之前,您不能添加ManyToMany關係,並且在save呼叫和self.tags.all()呼叫之間沒有時間設置它們。

2

您是否在使用django-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()