2016-04-08 44 views
0

我使用Django 1.7.11。我有模型:Django,保存更改模型时为ManyToManyField添加值

#I use django-categories app here 
class Category(CategoryBase): 
    pass 

class Advertisment(models.Model): 
    title = models.CharField(max_length=255, blank=True) 
    category = models.ForeignKey(Category, related_name='category') 
    all_categories = models.ManyToManyField(Category, blank=True, related_name='all_categories') 

我需要字段“all_categories”包含“类别”和它的所有父类别。我试图使用post_save,但它不会改变任何值。它甚至不会更改标题字段。当我通过管理界面创建模型并使用自定义窗体时,它不起作用。

@receiver(post_save, sender=Advertisment, dispatch_uid="update_stock_count") 
def update_stock(sender, instance, **kwargs):  
categ = instance.category  
instance.all_categories.add(categ)   
for parent in categ.get_ancestors(): 
      if parent not in instance.all_categories.all(): 
        instance.all_categories.add(parent) 

m2m_changed也没有帮助,因为ManyToManyField为空且没有更改。我如何将ForeignKey中的值添加到ManyToMany字段?我应该怎么做才能在管理界面中工作。

+0

你的'post_save'被调用了吗? –

+0

是的,现在我注意到它可以在自定义窗体中正常工作,并且不适用于管理界面。我能用管理员表单做什么?) – Swallow

回答

0

我找到了解决方案。在管理员类中需要添加一个像这样的函数save_model:

class AdvertismentAdmin(admin.ModelAdmin): 
    def save_model(self, request, obj, form, change):     
     if obj.category: 
     category_list=[] 
     category = obj.category 
     category_list.append(category) 
     for parent in category.get_ancestors(): 
      if parent not in category_list: 
       category_list.append(parent) 
     form.cleaned_data['all_categories'] = category_list    
     super(AdvertismentAdmin, self).save_model(request, obj, form, change)