Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM queries fail to select new objects

Setup:

  • Python script A inserts data to a DB every round 15 minutes
  • Python script B queries for the last 5 entries every few minutes

Both use django's ORM, same MySQL DB and the same DB user account (same settings.py file)

The Problem:
B is able to fetch only entries inserted before it was run. As if B is running with a frozen DB, frozen at the moment B first connected to the DB.

How come?
Can I control this behavior in django?

like image 961
Jonathan Livni Avatar asked Aug 11 '11 14:08

Jonathan Livni


People also ask

What is Django's ORM?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

Is Django ORM good?

The Django ORM is a very powerful tool, and one of the great attractions of Django. It makes writing simple queries trivial, and does a great job of abstracting away the database layer in your application. And sometimes, you shouldn't use it.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

Can I use Django without ORM?

Yes that is possible, but a lot of how Django can help is then not available. In that case, Django will look more (in terms of what it can do) like Flask.


1 Answers

If you're reusing same Manager object, you have to keep in mind it's caching. To deal with that you have to manually update.

This will return same results in every iteration:

while True:
   same_every_time = AClass.objects.all().order_by('-id')[:5]
   sleep(300)

In order to make it work properly you have to add the update:

while True:
   AClass.objects.update()
   updated_results = AClass.objects.all().order_by('-id')[:5]
   sleep(300)
like image 79
vartec Avatar answered Oct 11 '22 09:10

vartec