我正在尝试保存客户记录的现有实例。它的模型具有车辆模型的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。
最后,在this中的答案之后,我通过添加:
将其调整为我的方案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)
答案 0 :(得分: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