Reputation: 2738
I want to update only one field in my model. However, I am getting an error.
This is my model:
class People(models.Model):
name = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
class Salary(models.Model):
id_of_people=models.ForeignKey(People)
salary = models.IntegerField(required=False)
In views.py
-When I try this one to update :
def update(request):
a=Salary.objects.get(id_of_people_id=1)
a.salary=500
Salary().save()
My Error says:
IntegrityError at/update
salary.id_of_people_id may not be NULL
and traceback indicates:
Salary().save()
-When I try this one :
def update(request):
a=Salary.objects.get(id_of_people_id=1)
a.salary=500
Salary().save(save_fields=['salary'])
-I get this error:
save() got an unexpected keyword argument 'save_fields'
Can you please help me to update only one field in my table ?
Upvotes: 1
Views: 689
Reputation: 1961
If a ForeignKey is defined in your model, the contraint will be enforced at the db level so you will need to save the object reference by the Foreign key before you save the referring object.
You may also want to reconsider whether or not the foreign keys should be defined in person or Salary.
If you were to define the model like this:
class Person(models.Model):
name = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
salary = models.ForeignKey(Salary)
class Salary(models.Model):
amount = models.IntegerField(required=False)
Then you could define your views function so that it looks like this:
def update(request):
s = Salary(amount=request.POST['salary'])
s.save()
p = Person(name=request.POST['name'], lastname=request.POST['lastname'], salary=s)
p.save()
The nice about this is that you could then reference the salary from a Person instance:
Person.objects.get(pk=1).salary.amount
I can't help but ask the question though why you really need these in separate objects. Things might be simpler if your model looked like this:
class Person(models.Model):
name = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
salary = models.IntegerField(required=False)
Upvotes: 0
Reputation: 9890
In both of those cases you'll want to call save
on the model instance you've created, not the model class--that is, you should be saving a
, not Salary
:
a.salary=500
a.save()
When you do Salary().save()
, what's happening is that you create a brand new, empty model instance, and then try to commit that to the database, rather than committing the one that you had just modified.
Upvotes: 4