Django子继承对象无法看到M2M父属性

时间:2017-03-09 17:41:39

标签: python django django-models m2m django-inheritance

我有以下型号:

    from django.contrib.sites.models import Site

        class Entity(models.Model):
            name = models.CharField('Name', max_length=64) 
            desc = models.TextField('Description',)
            tags = models.ManyToManyField(Tag,related_name='companies')
            sites = models.ManyToManyField(Site)

    class Company(Entity):  
        founded_date = models.DateField(blank=True, null=True, help_text='Enter in YYYY-MM-DD format.')
        employee_amount = models.IntegerField('Number of Employees',blank=True, null=True)

class Employee(models.Model):  
    user = models.OneToOneField(User)  
    entity = models.ForeignKey('companies.Entity', blank=True, null=True)

我想第一次保存公司(添加)并更新(编辑)。

我在以下视图中这样做:

try:
            company = Company.objects.get(employee=get_employee(request.user))
            form = CompanyForm(request.POST, request.FILES, instance=company)
        except:
            form = CompanyForm(request.POST, request.FILES)


        if form.is_valid():
            company  = form.save(commit=False)

            if action == 'add':
                try:
                    entity = Entity.objects.get(name=company.name)
                    company = entity.company
                    employee.entity = entity
                    employee.save()
                except:
                    pass

            company.save()
            employee.entity = company
            employee.save()
            employee.entity.sites.add(current_site)
            company.save_m2m()

当我这样做时,我收到错误:

  

'公司'对象没有属性' save_m2m'

当父母"实体"有这个价值和孩子"公司"应该可以访问吗?

1 个答案:

答案 0 :(得分:1)

必须在表单上调用

save_m2m,而不是在模型实例上调用(请参阅this topic)。