django-queries

Django filter versus get for single object?

I was having a debate on this with some colleagues. Is there a preferred way to retrieve an object in Django when you're expecting only one? The two obvious ways are: try: obj = MyModel.objects.get(id=1) except MyModel.DoesNotExist: # we have no object! do something pass and objs = MyModel.objects.filt...

Is it possible to filter on a related item in Django annotations?

I have the following 2 models: class Job(models.Model): title = models.CharField(_('title'), max_length=50) description = models.TextField(_('description')) category = models.ForeignKey(JobCategory, related_name='jobs') created_date = models.DateTimeField(auto_now_add=True) class JobCategory(models.Model): title = m...

Caching of querysets and re-evaluation

Hi, I'm going to post some incomplete code to make the example simple. I'm running a recursive function to compute some metrics on a hierarchical structure. class Category(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='children', default=1) def compute_metrics(self, shop_object, metric_queryse...

How to sort by annotated Count() in a related model in Django

Hi, I'm building a food logging database in Django and I've got a query related problem. I've set up my models to include (among other things) a Food model connected to the User model through an M2M-field "consumer" via the Consumption model. The Food model describes food dishes and the Consumption model describes a user's consumption o...

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...

Is it possible to order_by with a callable?

DUPLICATE: http://stackoverflow.com/questions/981375/using-a-django-custom-model-method-property-in-orderby I have two models; one that stores posts and another that stores votes made on those posts, related using a ForeignKey field. Each vote is stored as a separate record since I need to track the user and datetime that the vote was...

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...

How to filter/exclude inactive comments from my annotated Django query?

I'm using the object_list generic view to quickly list a set of Articles. Each Article has comments attached to it. The query uses an annotation to Count() the number of comments and then order_by() that annotated number. 'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'), The comments a...

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...

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...

Django Query Question

I'm trying to query an object and when I hard code the value it works but when I use a variable for it the query doesn't work. Here's the class: class AdvertisementType(models.Model): type = models.CharField(max_length='40') description = models.CharField(max_length='80') def __unicode__(self): return '%s' % self.t...

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 Category and Subcategory searches

I'm attempting to use a similar Category implementation to this one in the Django Wiki. I'm wondering what the Django way of doing a search to pull all objects associated with a parent category. For example, if I have a category "TV" and it has subcategories "LED", "LCD", and "Plasma", how would I be able to easily query for all TV's w...

Django Query That Get Most Recent Objects From Different Categories

I have two models A and B. All B objects have a foreign key to an A object. Given a set of A objects, is there anyway to use the ORM to get a set of B objects containing the most recent object created for each A object Here's an simplified example: Class Bakery(models.Model): town = models.CharField() Class Cake(models.Model): ...

Using django.db.connection.queries ...

Hi, I've got a Python/Django application which runs quite a lot of SQL statements. For debugging purposes, I thought I should create a simple view for me which just lists all the SQL statements that have been run. According to the documentation, this code should be enough to do that: from django.db import connection connectio...

Django, updating from model

Hello, assume I have this little model: class Deal(models.Model): purchases = models.IntegerField(default=0)#amount of purchases so far increase_purchases(self,to_add): self.update( purchases =self.purchases + to_add) when I try to use this increase_purchases model from shell: >>> x = Deal.objects.get(id=1) >>> x.inc...

Count number of records by date in Django

I'm using Django 1.1 with MySQL as the database. I have a model similar to the following: class Review(models.Model): venue = models.ForeignKey(Venue, db_index=True) review = models.TextField() datetime_created = models.DateTimeField(default=datetime.now) I'd like to query the database to get the total number of reviews...

How do get the different values that takes an attribute with a django query ?

I have this Model in django : class Post(models.Model): title = models.CharField(max_length=255) category = models.CharField(max_length=255) I would like to get the different values that are used in the category attribute. For example, if we consider this db : Post(title = "title 1", category="foo") Post(title = "title 2", c...

Django filter vs exclude

Is there a difference between filter and exclude in django? If I have self.get_query_set().filter(modelField=x) and I want to add another criteria, is there a meaningful difference between to following two lines of code? self.get_query_set().filter(user__isnull=False, modelField=x) self.get_query_set().filter(modelField=x).exclude(u...

Django select distinct sum

I have the following (greatly simplified) table structure: Order: order_number = CharField order_invoice_number = CharField order_invoice_value = CharField An invoice number can be identical on more than one order (order O1 has invoice number I1, order O2 has invoice number I1, etc.). All the orders with the same invoice n...