更新Django中现有的M2M关系
我试图保存客户记录的现有实例。其车型拥有M2M车型(因为客户可以有多辆车)。在阅读了几个问题/答案后,我仍然不知道如何解决这个问题。更新Django中现有的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,但立即失败。
我错过了什么?
谢谢。
月1日编辑: 视图上的部分现在看起来:
customer_form = CustomerForm(request.POST, instance=customer[0])
customer_form.save()
customer_form.vehicle_id.add(current_vehicle)
你误会一个多对多字段是什么在这里:
customer_form.vehicle_id = current_vehicle.id
vehicle_id
被定义为一个多对多字段中输入您客户模型,因此你不能只分配一个单一的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
好的,在完成customer_form = CustomerForm(request.POST,instance = customer [0]),添加customer_form.save()和THEN customer_form.vehicle_id.add(current_vehicle)后,严格遵循您提供的django文档链接。不幸的是,在customer_form.save()行失败,并出现一个值错误(“客户无法更改,因为数据未验证”)。然而,request.POST确实有我做的改变,它只是在其中一个字段的末尾添加一个字母。顺便说一句,这仍然有足够的空间用于额外的角色。我究竟做错了什么? – Rmartin
请显示您的“客户”模型的完整源代码。当你在模型上调用'save()'时,它在模型上调用'full_clean',所以它在模型验证中失败 – Anentropic
FUll客户模型被添加。谢谢。 – Rmartin
车辆是否可以与多个客户关联?如果不是,那么我认为你的车型不正确,你应该在车型上有一个客户外键,并且根本没有M2M字段。请显示模型定义并显示您的完整视图。 –
你在什么版本的Django上? – Anentropic
是在原始源代码中正确缩进的保存方法的最后一行吗? – Anentropic