django-orm

Django order_by specific order

寵の児 提交于 2019-11-28 21:27:11
Is it possible to replicate this kind of specific sql ordering in the django ORM: order by (case when id = 5 then 1 when id = 2 then 2 when id = 3 then 3 when id = 1 then 4 when id = 4 then 5 end) asc ? You could do it w/ extra() or more plain raw() , but they can not work well w/ more complex situation. qs.extra(select={'o':'(case when id=5 then 1 when id=2 then 2 when id=3 then 3 when id=1 then 4 when id=4 then 5 end)', order_by='o'} YourModel.raw('select ... order by (case ...)') For your code, condition set is very limited, you could sort in Python easily. Since Django 1.8 you have

Django Admin ManyToManyField

给你一囗甜甜゛ 提交于 2019-11-28 20:30:17
I've made a model (models.py): class opetest(models.Model): name = models.CharField(max_length=200) author = models.ForeignKey(User, related_name='author') description = models.TextField(u'Test description', help_text = u'Some words about quiz') pub_date = models.DateTimeField('date published', blank=False) vacancies = models.ManyToManyField(Vacancy, blank=True) students = models.ManyToManyField(User, blank=True, related_name='opetests') #This field I want to edit on "User change page" estimate = models.IntegerField(default = 0, help_text = u'Estimate time in hours. \'0\' - unlimited') then I

How to force Django Admin to use select_related?

≡放荡痞女 提交于 2019-11-28 20:07:25
问题 One of my models is particularily complex. When I try to edit it in Django Admin it performs 1042 queries and takes over 9 seconds to process. I know I can replace a few of the drop-downs with raw_id_fields , but I think the bigger bottleneck is that it's not performing a select_related() as it should. Can I get the admin site to do this? 回答1: Although dr jimbob's answer makes sense, for my needs, I was able to simply override the get_queryset() method with a one-liner, even selecting a

prefetch_related for multiple Levels

大城市里の小女人 提交于 2019-11-28 18:40:50
If my Models look like: class Publisher(models.Model): pass class Book(models.Model): publisher = models.ForeignKey(Publisher) class Page(models.Model): book = models.ForeignKey(Book) and I would like to get the queryset for Publisher I do Publisher.object.all() . If then want to make sure to prefetch I can do: Publisher.objects.all().prefetch_related('book_set')` My questions are: Is there a way to do this prefetching using select_related or must I use prefetch_related ? Is there a way to prefetch the page_set ? This does not work: Publisher.objects.all().prefetch_related('book_set', 'book

In a Django QuerySet, how to filter for “not exists” in a many-to-one relationship

百般思念 提交于 2019-11-28 18:18:35
问题 I have two models like this: class User(models.Model): email = models.EmailField() class Report(models.Model): user = models.ForeignKey(User) In reality each model has more fields which are of no consequence to this question. I want to filter all users who have an email which starts with 'a' and have no reports. There will be more .filter() and .exclude() criteria based on other fields. I want to approach it like this: users = User.objects.filter(email__like = 'a%') users = users.filter(

Django, query filtering from model method

安稳与你 提交于 2019-11-28 18:05:45
I have these models: def Foo(Models.model): size = models.IntegerField() # other fields def is_active(self): if check_condition: return True else: return False def Bar(Models.model): foo = models.ForeignKey("Foo") # other fields Now I want to query Bars that are having active Foo's as such: Bar.objects.filter(foo.is_active()) I am getting error such as SyntaxError at / ('non-keyword arg after keyword arg' How can I achieve this? You cannot query against model methods or properties. Either use the criteria within it in the query, or filter in Python using a list comprehension or genex. You

Django values_list vs values

烂漫一生 提交于 2019-11-28 15:45:59
In Django, what's the difference between the following two: Article.objects.values_list('comment_id', flat=True).distinct() vs Article.objects.values('comment_id').distinct() My goal is to get a list of unique comment ids under each Article . I've read the documentation (and in fact have used both approaches). The results overtly seem similar. The values() method returns a QuerySet containing dictionaries: <QuerySet [{'comment_id': 1}, {'comment_id': 2}]> The values_list() method returns a QuerySet containing tuples: <QuerySet [(1,), (2,)]> If you are using values_list() with a single field,

Select distinct values from a table field

不羁的心 提交于 2019-11-28 15:33:47
I'm struggling getting my head around the Django's ORM. What I want to do is get a list of distinct values within a field on my table .... the equivalent of one of the following: SELECT DISTINCT myfieldname FROM mytable (or alternatively) SELECT myfieldname FROM mytable GROUP BY myfieldname I'd at least like to do it the Django way before resorting to raw sql. For example, with a table: id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 4, Another Way, Leicester 5, High Street, Londidium I'd like to get: Hull, Leicester, Londidium. Say your model is 'Shop'

How to perform OR condition in django queryset?

99封情书 提交于 2019-11-28 14:49:48
问题 I want to write a Django query equivalent to this SQL query: SELECT * from user where income >= 5000 or income is NULL. How to construct the Django queryset filter? User.objects.filter(income__gte=5000, income=0) This doesn't work, because it AND s the filters. I want to OR the filters to get union of individual querysets. 回答1: from django.db.models import Q User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True)) via Documentation 回答2: Because QuerySets implement the Python __or__

How to map PostgreSQL array field in Django ORM

与世无争的帅哥 提交于 2019-11-28 11:58:43
I have an array field in my PostrgreSQL database of type text. Is there a way to map this into a Django model ? You might want to look into django-dbarray on github. It adds support for postgresql array fields. I haven't used it before, but it looks like you just need to do: from django.db import model import dbarray class ProfilingTestRun(models.Model): function = models.CharField(max_length=64) runtimes = dbarray.FloatArrayField() One of the other nice options is http://django-orm.readthedocs.org/ --- a library that adds bindings to many native postgres types. Main drawback of django-orm is