Django objects.filter does not update the field, but object.get

I have a Django model:

class QuestionAnswer(models.Model):
   question = models.ForeignKey(Question)
   marks = models.FloatField(null=True)
   graded = models.IntegerField()

Now at the command prompt:

>>> qa = QuestionAnswer.objects.filter(pk=12345)
>>> qa[0].graded 
0
>>> qa[0].graded = 1
>>> qa[0].save()
>>> qa = QuestionAnswer.objects.filter(pk=12345)
>>> qa.graded
0

The field is gradednot updated.

But when I do this:

>>> qa = QuestionAnswer.objects.get(pk=12345)
>>> qa.graded 
0
>>> qa.graded = 1
>>> qa.save()
>>> qa = QuestionAnswer.objects.get(pk=12345)
>>> qa.graded
1

Why objects.filterdoesn't it update the field, but it objects.getworks?

+4
source share
3 answers

Try the following:

>>> qs = QuestionAnswer.objects.filter(pk=12345)
>>> qa = qs[0]
>>> qa.graded
0
>>> qa.graded = 1
>>> qa.save()
>>> qa = QuestionAnswer.objects.filter(pk=12345)
>>> qa[0].graded
This should be 1

Using qa[0], you do not actually modify or save the same object (even if they represent the same SQL data).

, : sql , , . , , . , , qa[0], . , , :

>>> qs = QuestionAnswer.objects.filter(pk=12345)
>>> qa1 = qs.get()
>>> qa1.graded
0
>>> qa2 = qs.get()
>>> qa2.graded = 1
>>> qa3 = qs.get()
>>> qa3.save()

, qa1, qa2 qa3 - : ( ), . graded qa2 qa3, , qa3 , qa2 .

, , , :

>>> qs = QuestionAnswer.objects.filter(pk=12345)
>>> qs[0] is qs[0]
False # These are not the same objects in memory...
>>> bool(qs) # This forces evaluation of the entire queryset
True
>>> qs[0] is qs[0]
True # ... but these are!
>>> qs[0].graded
0
>>> qs[0].graded = 1
>>> qs[0].save()
>>> qs = QuestionAnswer.objects.filter(pk=12345)
>>> qs[0].graded
1
+7

, ORM

QuestionAnswer.objects.filter(pk=12345).update(graded=1)
+3

filter a QuerySet ( ). django , , .

get , ""; , -, .

To solve your problem, you need to evaluate the request. You can do this by iterating over it (in a for loop) or converting it to a list.

However, since you are filtering the primary key, you should still use get; but keep in mind that it getwill throw an exception when the key is not found, or when several objects are returned:

try:
   foo = Foo.objects.get(pk=-1)
except Foo.DoesNotExist:
   print('There is no foo with pk 1')
except Foo.MultipleObjectsReturned:
   print('Oh no! Multiple foos with key 1!')

print('I am the foo with key 1: {}'.format(foo))
+2
source

Source: https://habr.com/ru/post/1535872/


All Articles