Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django accessing filter results by index doesnt save it to models

Model:

class faqs(models.Model):
 id = models.AutoField(primary_key=True)
 question=models.TextField()
 answer=models.TextField()
 category=models.CharField(max_length=200,null=True)
 frequency=models.IntegerField(max_length=10, blank = True, null = True)
 class Meta:
    db_table='faqs'

The folloing does'nt save it to DB,

s=faqs.objects.filter(id=1)
s[0].id=111
s[0].save()

But this saves the upadted value to DB,

s=faqs.objects.filter(id=1)[0]
s.id=111
s.save()

Why is not django not allowing to save values via the first method

like image 375
Vivek S Avatar asked Oct 26 '25 20:10

Vivek S


1 Answers

The issue is that each time you slice the queryset, Django hits the database and creates a new instance. So the instance you set the id on is not the same instance as the one you call save() on - remember that Django instances do not have identity, and that separate objects that refer to the same database row don't share anything.

You can see what's happening if you examine the database queries: you'll see that no queries are executed for the first line, the filter. A SELECT is executed for the second line - but it only gets one instance, using a LIMIT 1. And an identical SELECT is executed for the third line, giving you a completely new instance.

You've already seen one way round this. The other way is to force the entire queryset to be executed after the filter, but calling list on the result.

like image 121
Daniel Roseman Avatar answered Oct 29 '25 13:10

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!