我使用Django 1.7.11。我有模特:
csv1 = pd.read_csv('data1.csv')
csv2 = pd.read_csv('data2.csv')
csv3 = pd.merge(csv1,csv2, on='ID_NUMBER', how='inner')
#csv3 will have columns like ['ID_NUMBER', 'CHECKING_CODE_x', 'SECURITY_CODE_x', 'JOB_ID_x', 'CHECKING_CODE_y', 'SECURITY_CODE_y', 'JOB_ID_y']]
csv3['CHECKING_CODE'] = csv3.CHECKING_CODE_x == csv3.CHECKING_CODE_y
csv3['SECURITY_CODE'] = csv3.SECURITY_CODE_x == csv3.SECURITY_CODE_y
csv3['JOB_ID'] = csv3.JOB_ID_x == csv3.JOB_ID_y
csv_out = csv3[['ID_NUMBER','CHECKING_CODE',''SECURITY_CODE','JOB_ID']]
我需要字段" all_categories"包含"类别"以及它的所有父类别。我尝试使用post_save,但它并没有改变任何值。它甚至不会改变标题字段。当我通过管理界面创建模型并使用自定义表单时,它不起作用。
#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')
m2m_changed也没有帮助,因为ManyToManyField为空并且没有任何更改。如何将ForeignKey中的值添加到ManyToMany字段?我应该怎么做才能在管理界面中使用。
答案 0 :(得分:0)
我找到了解决方案。在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)