Django,在保存模型更改时为ManyToManyField添加值

时间:2022-11-15 20:03:51

I use Django 1.7.11. I have models:

我使用Django 1.7.11。我有模特:

#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')

I need field "all_categories" contains "category" and all it's parent categories. I tried to use post_save, but it doesn't change any value. It even doesn't change title field. It doesn't work when I create model throught admin interface and works with custom form.

我需要字段“all_categories”包含“category”及其所有父类别。我试图使用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 doesn't help too because ManyToManyField is empty and has no changes. How can I add a value from ForeignKey to ManyToMany field? What should I do in order to it works in admin interface.

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

1 个解决方案

#1


0  

I've found the solution. In admin class need to add a function save_model like this:

我找到了解决方案。在admin类中需要像这样添加一个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)

#1


0  

I've found the solution. In admin class need to add a function save_model like this:

我找到了解决方案。在admin类中需要像这样添加一个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)