Sahana Prabhakar
Sahana Prabhakar

Reputation: 581

updating unique field values django creates a new row

I have a model which has a field with unique constraint. When I try to update the unique field value, a new row is created instead of updating the old one. Did refer to few other queries but couldnt find a solution. Below is my model :

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

and 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')

I am calling my save_aircrafts method from my html file.

Upvotes: 1

Views: 1816

Answers (1)

zaidfazil
zaidfazil

Reputation: 9235

You could use get_or_create function,

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

Upvotes: 1

Related Questions