When to use force_update in Django's save()? - python

Django official docs state that:
In some rare circumstances, it’s necessary to be able to force the save() method to perform an SQL INSERT and not fall back to doing an UPDATE. Or vice-versa: update, if possible, but not insert a new row. In these cases you can pass the force_insert=True or force_update=True parameters to the save() method. Obviously, passing both parameters is an error: you cannot both insert and update at the same time!
What are these rare circumstances?
Basically, when should one use force_update=True?

Related

Need to save after QuerySet update?

I need to updates all the entries in my database that meet a certain condition. I can obtain them by filtering the correspondent model and update them using the update method on the obtained QuerySet, but I don't know if I have to execute the save method on every object of the QuerySet to save the changes or if the changes are saved to the DB automatically.
As the docs explain, if you call QuerySet.update, that translates to a single UPDATE SQL query, so its effects are applied right away. The update method doesn't even return a QuerySet anymore, so you can't even iterate over it. It will return the number of affected objects instead.

When is from_db_value called in Django 1.8?

In the Django 1.8 release notes, it mentions that Django Fields no longer use SubfieldBase, and has replaced the to_python call on assignment with from_db_value.
The docs also state that from_db_value is called whenever data is loaded from the database.
My question is, is from_db_value called if I directly read/write the db (i.e. using cursor.execute())? My initial tries and intuition says no, but I just want to make sure.
See The Django Documentation for Executing custom SQL directly.
Sometimes even Manager.raw() isn’t quite enough: you might need to perform queries that don’t map cleanly to models, or directly execute UPDATE, INSERT, or DELETE queries.
In these cases, you can always access the database directly, routing around the model layer entirely.
The above states that using cursor.execute() will bypass the model logic entirely, returning the raw row results.
If you want to perform raw queries and return model objects, see the Django Documentation on Performing raw queries.
The raw() manager method can be used to perform raw SQL queries that return model instances:
for p in Person.objects.raw('SELECT * FROM myapp_person'):
print(p)
>>> John Smith
>>> Jane Jones

get_or_create in Peewee

The paragraph titled Get or create on the peewee documentation says:
While peewee has a get_or_create() method, this should really not be
used outside of tests as it is vulnerable to a race condition. The
proper way to perform a get or create with peewee is to rely on the
database to enforce a constraint.
And then it goes on with an example that only shows the create part, not the get part.
What is the best way to perform a get or create with peewee?
Everything you are doing inside a transaction is atomic.
So as long as you are calling get_or_create() inside a transaction, that paragraph is wrong.

How can I quickly set a field of all instances of a Django model at once?

To clarify, I've got several thousands of Property items, each with a 'present' field (among others). To reset the system for use again, I need to set every item's 'property' field to false. Now, of course there's the easy way to do it, which is just:
for obj in Property.objects.all():
obj.present = False
obj.save()
But this takes nearly 30 seconds on my development server. I feel there must be a better way, so I tried limiting the loaded fields using Django's only queryset:
for obj in Property.objects.only('present'):
obj.present = False
obj.save()
For whatever reason, this actually takes longer than just getting the entire object.
Because I need to indiscriminately set all of these values to False, is there a faster way? This function takes no user input other than the 'go do it' command, so I feel a native SQL command would be a safe option, but I don't know SQL enough to draft such a command.
Thanks everyone.
Use the update query:
Property.objects.all().update(present=False)
Note that update() query runs at SQL level, so if your model has a custom save() method then it is not going to be called here. In that case, the normal for-loop version that you're using is the way to go.

When are property validations run in Google App Engine (GAE)?

So I was reading the following documentation on defining your own property types in GAE. I noticed that I could also include a .validate() method when extending a new Property. This validate method will be called "when an assignment is made to a property to make sure that it is compatible with your assigned attributes". Fair enough, but when exactly is that?
My question is, when exactly is this validate method called? Specifically, is it called before or after it is put? If I create this entity in a transaction, is validate called within the transaction or before the transaction?
I am aware that optimally, every Property should be "self contained" or at most, it should only deal with the state of the entity is resides in. But, what would happen if you performed a Query in the validate method? Would it blow up if you did a Query within validate that was in a different entity group than your current transactions entity group?
Before put, and during the transaction, respectively (it may abort the transaction if validation fails of course). "When an assignment is made" to a property of your entity is when you write theentity.theproperty = somevalue (or when you perform it implicitly).
I believe that queries of unrelated entities during a transaction (in validate or otherwise) are non-transactional (and thus very iffy practice), but not forbidden -- but on this last point I'm not sure.

Categories