Python 更新唯一字段值django将创建新行
我有一个模型,它有一个具有唯一约束的字段。当我尝试更新唯一字段值时,将创建一个新行,而不是更新旧行。确实提到了一些其他问题,但找不到解决方案。以下是我的模型:Python 更新唯一字段值django将创建新行,python,django,Python,Django,我有一个模型,它有一个具有唯一约束的字段。当我尝试更新唯一字段值时,将创建一个新行,而不是更新旧行。确实提到了一些其他问题,但找不到解决方案。以下是我的模型: class AircraftType(models.Model): aircraft_id = models.AutoField(null=False, primary_key=True) aircraft_type = models.CharField(max_length=20, null=False, blank=F
class AircraftType(models.Model):
aircraft_id = models.AutoField(null=False, primary_key=True)
aircraft_type = models.CharField(max_length=20, null=False, blank=False, unique=True)
aircraft_description = models.TextField()
和my views.py:
def save_aircrafts(request):
print "save_aircrafts"
aircraft_type = request.POST.get('aircrafttype')
print str("Save aircraft_type ") + aircraft_type
aircraft_instance = AircraftType.objects.filter(aircraft_type=aircraft_type)
if aircraft_instance.exists():
print str("aircraft_instance.exists") + aircraft_type
aircraft_instance.update(aircraft_type=aircraft_type)
aircraft_instance.aircraft_type = aircraft_type
aircraft_instance.save()
else:
print str("aircraft_instance.NOTexists") + aircraft_type
AircraftType.objects.create(aircraft_type=aircraft_type)
return redirect('aircraft_list')
我正在从我的html文件中调用我的
save\u aircrafts
方法 您可以使用get\u或\u create
函数
aircraft_instance, created = AircraftType.objects.get_or_create(aircraft_type=aircraft_type)
if created:
print "New object has been created"
else:
#Do what you want to do with instance.
aircraft_instance.save()
你永远不能进入
if
块,因为你会得到一个名称错误:你混淆地调用aircraft\u实例的东西实际上不是一个实例,而是一个查询集,而那些没有save
方法。因此,您必须始终进入else
块:大概是因为您用于aircrafttype
的值不在数据库中。您的print语句显示了什么?@Daniel exists()是过滤查询集上的有效方法。虽然你关于保存方法不可用的观点是正确的。是的,我没有说它不可用<代码>存在
只在查询集上有效,这根本不是问题。@DanielRoseman-非常感谢!。你去else街区是对的<代码>飞机\实例。更新(飞机\类型=飞机\类型)单独为我工作。