2010-01-21 3 views
1

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?? 

답변

0

카드에 태그를 추가하지 않았습니다. 카드를 저장하기 전까지 ManyToMany 관계를 추가 할 수 없으므로 save 통화와이 번호를 설정하기위한 시간은 self.tags.all() 사이입니다.

2

django-admin을 사용하여 모델과 태그를 저장하고 있습니까? 다 대다 필드는 모델의 post-save 신호 이후에 저장되지 않습니다. 이 경우 관리자가 수행 할 수있는 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()