In the end I've found what is causing this problem. It was my own caching code rather than Django's.
I had custom Source manager in place, which returned and cached some standard source:
class SourceManager(models.Manager):
url_source = None
def get_generic(self):
if self.url_source is None:
self.url_source, created = self.get_or_create(name = 'URL', quality = 0)
return self.url_source
class Source(models.Model):
name = models.CharField(max_length = 50)
quality = models.IntegerField(default = 0)
objects = SourceManager()
This works perfectly fine in the application - once source is created, the manager remembers it for it's existence as the sources do not change over their lifetime. However in tests they go away as the whole test is run in single transaction and then reverted.
What I find strange is that models.ForeignKey
did not complain about getting non existing object, but the error appeared later, while sorting by source__quality
as the underlaying JOIN SELECT could not find matching Source
object.