【问题标题】:Save method manytomany保存方法manytomany
【发布时间】:2010-01-21 09:17:03
【问题描述】:

我有一个名为 Card 的模型,它与 标签。当我保存一张卡片时,我也想创建一个产品,我 希望与标记具有相同的多对多关系。

如何访问实例的标签? 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?? 

【问题讨论】:

    标签: python django methods save many-to-many


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您没有向卡片添加任何标签。在保存卡片之前,您无法添加多对多关系,并且在 save 调用和对 self.tags.all() 的调用之间没有时间来设置它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 2020-09-03
        相关资源
        最近更新 更多