django-queryset

django queryset: how to order by a (backwards) related field?

Hi folks! In this situation I have two models, Comment and Score. The relationship is defined in the Score model, like so: class Comment(models.Model): content = TextField() ... class Score(models.Model): comment = models.ForeignKey(Comment) value = models.IntegerField() My question is: How do I construct a queryset ...

Order queryset on calculated field

I have the following problem. I have these 3 models class Model1(models.Model): name = models.CharField() class Model2(models.Model): user = models.ForeignKey(User) parent = models.ForeignKey(Model1) class Model3(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, verbose...

How can I get previous and next objects from a filtered, ordered queryset?

I have a page based on a model object, and I want to have links to the previous and next pages. I don't like my current solution because it requires evaluating the entire queryset (to get the ids list), and then two more get queries. Surely there is some way this can be done in one pass? def get_prev_and_next_page(current_page): ids...

Django annotate to show aggregate sums and counts pre-slicing of the QuerySet

I have a fairly complex QuerySet which users a good deal of annotated values to get some counts and sums across the entire record set. The resulting rows are grouped and for each group I show the sum of this column, or the count of that column etc. The problem is that when I slice the query set in order to paginate the data, the query i...

django: time range based aggregate query

Hi there! I have the following models, Art and ArtScore: class Art(models.Model): title = models.CharField() class ArtScore(models.Model): art = models.ForeignKey(Art) date = models.DateField(auto_now_add = True) amount = models.IntegerField() Certain user actions results in an ArtScore entry, for instance whenever y...

What is simplest way join __contains and __in?

I am doing tag search function, user could observe a lot of tags, I get it all in one tuple, and now I would like to find all text which include at least one tag from the list. Symbolic: text__contains__in=('asd','dsa') My only idea is do loop e.g.: q = text.objects.all() for t in tag_tuple: q.filter(data__contains=t) EDIT: Now...

A puzzle concerning Q objects and Foreign Keys

I've got a model like this: class Thing(models.Model): property1 = models.IntegerField() property2 = models.IntegerField() property3 = models.IntegerField() class Subthing(models.Model): subproperty = models.IntegerField() thing = modelsForeignkey(Thing) main = models.BooleanField() I've got a function that is...

Customize count list

I have this code I'm using to generate a list of records categorized into year, make, series, body style, and color for vehicles. I'd like to customize this further this way: for the year, I want to have only up to 2004 being individual...the rest will fall under other i.e. 2009, 2008, 2007, 2006, 2005, 2004, Other. for the make, I wa...

How to enforce account based separation in Django

I have a Django app which has a single-account model. We are converting this to be multi-account, so almost every model will have a ForeignKey(Account). What is the easiest way to make sure that each Account (each account is in its own subdomain) can only access its own data? We have a middleware that populates the subdomain, and the cu...

How to properly query a ManyToManyField for all the objects in a list (or another ManyToManyField)?

I'm rather stumped about the best way to build a Django query that checks if all the elements of a ManyToMany field (or a list) are present in another ManyToMany field. As an example, I have several Persons, who can have more than one Specialty. There are also Jobs that people can start, but they require one or more Specialties to be el...

fast lookup for the last element in a Django QuerySet?

I've a model called Valor. Valor has a Robot. I'm querying like this: Valor.objects.filter(robot=r).reverse()[0] to get the last Valor the the r robot. Valor.objects.filter(robot=r).count() is about 200000 and getting the last items takes about 4 seconds in my PC. How can I speed it up? I'm querying the wrong way? ...

Django's list_details views saving queryset to memory (not updating)?

I have a custom model manager that looks like this: class MyManager(models.Manager) def get_query_set(self): '''Only get items that are 'approved' and have a `pub_date` that is in the past. Ignore the rest.''' queryset = super(MyManager, self).get_query_set() queryset = queryset.filter(status__in=('a...

Django: filtering models on the difference of Counts of related models

I've got a bunch of Order objects, each connected to one or more OrderRow objects (visible as a reverse relation to their parent Orders with Order.order_rows.all()). Each OrderRow has a collection_status attribute, which can be 'collected', 'uncollected' or a bunch of other special values. Each Order has a status attribute, one of the v...

Use <optgroup> with form.fields.queryset?

Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in <optgroup>'s? Here is what I have: views.py form = TemplateFormBasic(initial={'template': digest.template.id}) form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.user)).order_by('...

django queryset datetime values substraction

Hello, I have model with following field. date = models.DateTimeField(auto_now_add=True) When querying such model i`d like to have additional column that would keep difference between current date and previous one. So for 10 rows it would have 9 values, first one would be None. Are there any ways of achieving this with querysets? or m...

Trying to sort queryset...

Hi. I have model like this: class Kaart(models.Model): name = models.CharField(max_length=200, verbose_name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False) url = models.CharField(max_length=200, blank=False, null=False, verbose_name="Asukoha URL", help_text="Täisa...

How can i add key/value to object queryset

Hi I need to add key/value to queryset per each object based on stuff in request.session. How to do that? Alan ...

Implementating a logical parser in django-query

This is going to be a "long one". I'm including as much code and explanation as possible ... I'm not above throwing out code if necessary. I'm trying to implement a logical parser in a django query system. Where users can provide complex queries against tags that are applied to samples. This is essentially part of a scientific sample...

Sort by display name instead of actual value

Consider this sample model: MODEL_CHOICES = ( (u"SPAM", u"Spam"), (u"XOUP", u"Eggsoup"), ) (snip) type = models.CharField(max_length=4, choices=MODEL_CHOICES) (The actual implementation is domain-specific and in non-English, so this sample has to do.) When building my query, I'd like to sort the results by that...

Django: get parent objects matching condition on child

Couldn't think of a more appropriate question title, but I'm looking for some advice on how to implement the following requirement: I have a Project class, which may contain Task objects. Tasks have an assignee. In my Django template, I'd like to render a 'tree' of projects and tasks for a given user, showing only those projects that ha...