我有一个具有唯一约束的字段的模型。当我尝试更新唯一字段值时,会创建一个新行而不是更新旧行。提到了一些其他查询,但无法找到解决方案。以下是我的模特:
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')
和我的views.py:
save_aircrafts
我从我的html文件调用我的fiscale:marco
esposito:ronaldo
方法。
答案 0 :(得分:0)
您可以使用get_or_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()