django-orm

Order Django objects randomly.

Here's an interesting problem, I have a list of users that I list in order of rating, and where two users have the same rating, I have a random number that I use to make sure the list won't always be the same. Currently I do this by executing a query: select app_model1.column1, app_model1.colum2, app_model2.column3 from app_mode...

Is there a way to make a query respect the order of the inputted parameters?

(Please let me know if this is completely absurd, that is probably a reason why I haven't found anything on this.) This story has two models Ranking and Artist, Ranking is generically related to Artist (object_id, content_type... the whole shebang). I have a list of objects returned by Ranking.objects.values_list() ordered by a certain...

Django generic relations practice

Hi! i'm developing a authentication backend with object-based permissions for my django-app.I use generic relations between an object and a permission: class GroupPermission(models.Model): content_t= models.ForeignKey(ContentType,related_name='g_content_t') object_id = models.PositiveIntegerField() content_object = generic.G...

Can Django do nested queries and exclusions

I need some help putting together this query in Django. I've simplified the example here to just cut right to the point. MyModel(models.Model): created = models.DateTimeField() user = models.ForeignKey(User) data = models.BooleanField() The query I'd like to create in English would sound like: Give me every record that w...

Django: Group by?

I'm looking for something like the following: previous_invoices = Invoice.objects.filter(is_open=False).order_by('-created').group_by('user') (group_by() doesn't exist) This would find the most recently closed invoice for each user. This aggregation API seems to let you do stuff like this for counts and sums, but I don't need a coun...

Model in sub-directory via app_label?

In order to place my models in sub-folders I tried to use the app_label Meta field as described here. My directory structure looks like this: project apps foo models _init_.py bar_model.py In bar_model.py I define my Model like this: from django.db import models class SomeModel(models.Model): field = models.Tex...

Tricky model inheritance - Django

Hi folks, I think this is a bit tricky, at least for me. :) So I have 4 models Person, Singer, Bassist and Ninja. Singer, Bassist and Ninja inherit from Person. The problem is that each Person can be any of its subclasses. e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a Ninja. Another one can be a...

Popularity Algorithm - SQL / Django

Hi folks, I've been looking into popularity algorithms used on sites such as Reddit, Digg and even Stackoverflow. Reddit algorithm: t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes y = {1 if x > 0, 0 if x = 0, -1 if x < 0) z = {1 if x < 0, otherwise x} log(z) + (y * t)/45000 I have always performed simple orderin...

Can this be done with the ORM? - Django

Hi folks, I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z=x return (log(z) + y * t/45000) I'm wonde...

Django: ordering by backward related field property

Hello! I have two models related one-to-many: a Post and a Comment: class Post(models.Model): title = models.CharField(max_length=200); content = models.TextField(); class Comment(models.Model): post = models.ForeignKey('Post'); body = models.TextField(); date_added = models.DateTimeField(); I want to get...

Django automatically compress Model Field on save() and decompress when field is accessed

Given a Django model likeso: from django.db import models class MyModel(models.Model): textfield = models.TextField() How can one automatically compress textfield (e.g. with zlib) on save() and decompress it when the property textfield is accessed (i.e. not on load), with a workflow like this: m = MyModel() textfield = "Hello, ...

Django QuerySet filter method returns multiple entries for one record

Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria: Blog.objects.filter(entries__title__contains='entry') The results is: [<Blog: blog1>, <Blog: blog1>] The same blog object is retrieved twice because of JOIN performed to filter objects on related model. What is the right syntax for...

Asynchronous daemon processing / ORM interaction with Django

I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to achieve asynchrony is? Basically what I need to accomplish is taking a list of use...

Annotate over Multi-table Inheritance in Django

I have a base LoggedEvent model and a number of subclass models like follows: class LoggedEvent(models.Model): user = models.ForeignKey(User, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class AuthEvent(LoggedEvent): good = models.BooleanField() username = models.CharField(max_length=12) c...

Django aggregation query on related one-to-many objects

Here is my simplified model: class Item(models.Model): pass class TrackingPoint(models.Model): item = models.ForeignKey(Item) created = models.DateField() data = models.IntegerField() class Meta: unique_together = ('item', 'created') In many parts of my application I need to retrieve a set of Item's and a...

Efficient query with Generic Relations

These are my models: class Comment(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object ID')) content_object = generic.GenericForeignKey() user = models.ForeignKey(User) comment = models.TextField(_('comment')) class Post(models.Model): title = models....

Django: select_related and GenericRelation

Does select_related work for GenericRelation relations, or is there a reasonable alternative? At the moment Django's doing individual sql calls for each item in my queryset, and I'd like to avoid that using something like select_related. class Claim(models.Model): proof = generic.GenericRelation(Proof) class Proof(models.Model): ...

Django: Sum on an date attribute grouped by month/year

Hello, I'd like to put this query from SQL to Django: "select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;" The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work : HourEntries.object...

Get number of results from Django's raw() query function

I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way? edit .count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count' ...

Django QuerySet filter + order_by + limit

So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1] median_score = median_ex...