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