2017-06-29 48 views
0

我有一个模型,它具有唯一约束的字段。当我尝试更新唯一字段值时,会创建一个新行而不是更新旧行。有没有提到其他一些查询,但无法找到解决方案。下面是我的模型:更新唯一字段值django创建一个新行

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() 

,我的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') 

我打电话我save_aircrafts方法从我的HTML文件。

+3

你永远不能将渐入'if'块,因为你会得到一个NameError:你已经被称为混淆的东西'aircraft_instance'是实际上不是一个实例,而是一个QuerySet,而那些没有'save'方法。因此,您必须*总是*进入'else'块:可能是因为您正在使用'aircrafttype'的值在数据库中已经不是*了。你的印刷报表显示什么? –

+0

@Daniel exists()是过滤查询集合的有效方法。 https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.exists,虽然你关于保存方法不可用的观点是正确的。 –

+0

是的,我没有说它不是。 'exists' *只*用于查询集,根本不是问题。 –

回答

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() 
相关问题