0

我正在尝试保存客户记录的现有实例。它的模型对车辆模型具有 M2M(因为客户可以多辆车)。在这里阅读了几个问题/答案后,我仍然不知道如何解决这个问题。

客户型号:

class Customer(models.Model):
    vehicle_id = models.ManyToManyField(VehicleSale)
    name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
                                     verbose_name='name')
    lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
                                verbose_name='license')
    addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
    city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
    state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
    zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
    email = models.EmailField(blank=True, null=True, verbose_name='email')
    tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
    tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
    ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')

    class Meta:
        db_table = 'customer'

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.name = self.name.upper()
        self.addr = self.addr.upper()
        self.city = self.city.upper()
        self.state = self.state.upper()

        return super(Customer, self).save(*args, **kwargs)

在视图中,定义客户为

customer = current_vehicle.customer_set.all()

我尝试了以下方法:

if 'customer' in request.POST:
    if customer:
        customer_form = CustomerForm(request.POST, instance=customer[0])
        if customer_form.is_valid():
            customer_form.save()

还尝试在定义 customer_form 之前添加:

customer.vehicle_id = current_vehicle.id

然后在表格之后:

customer_form.vehicle_id = current_vehicle.id

表单无效,因此未保存。在检查 {{ form.errors}} 时,它总是报告vehicle_id 是必需的。

最后,在这个答案之后我通过添加以下内容将其调整为我的场景:

obj = customer_form.save(commit=False)

并希望分配vehicle_id,但它立即失败。

我错过了什么?

谢谢。

第一次编辑:视图部分现在如下所示:

customer_form = CustomerForm(request.POST, instance=customer[0])
customer_form.save()
customer_form.vehicle_id.add(current_vehicle)
4

1 回答 1

1

您误解了这里的 ManyToMany 字段:

customer_form.vehicle_id = current_vehicle.id

vehicle_id被定义为 Customer 模型上的 ManyToMany 字段,因此您不能只为其分配一个 id。您必须添加VehicleSale模型实例,例如:

customer_form.vehicle_id.add(current_vehicle)

在此处查看文档:
https ://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

vehicle_id另请参阅此答案,了解为什么在填充关系之前无法保存:
https ://stackoverflow.com/a/2529875/202168

于 2014-02-05T16:29:31.607 回答