django filter with list of values

I'm sure this is a trivial operation, but I can't figure out how it's done... How can I create a django query for a list of values. There got to be something smarter than this: ids = [1, 3, 6, 7, 9] for id in ids: MyModel.objects.filter( pk=id ) I'm looking to get them all in one show with something like: ids = [1, 3, 6, 7, 9] MyModel.objects.filter( pk=ids ) 从Django文档

带有值列表的Django过滤器

我确定这是一个微不足道的操作,但我无法弄清楚它是如何完成的......我如何为值列表创建一个django查询。 有一些比这更聪明的东西: ids = [1, 3, 6, 7, 9] for id in ids: MyModel.objects.filter( pk=id ) 我期待着让他们在一个节目中看到像这样的东西: ids = [1, 3, 6, 7, 9] MyModel.objects.filter( pk=ids ) 从Django文档: Blog.objects.filter(pk__in=[1, 4, 7]) 当你有项目列表,你想检查列表中可能的值,那

Fastest way to get the first object from a queryset in django?

Often I find myself wanting to get the first object from a queryset in Django, or return None if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant. qs = MyModel.objects.filter(blah = blah) if qs.count() > 0: return qs[0] else: return None Does this result in two database calls? That seems wasteful. Is this a

从django的查询集中获取第一个对象的最快方法是什么?

我经常发现自己想要从Django中的查询集中获取第一个对象,如果没有,则返回None 。 有很多方法可以做到这一点。 但我想知道哪个是最高性能的。 qs = MyModel.objects.filter(blah = blah) if qs.count() > 0: return qs[0] else: return None 这是否会导致两个数据库调用? 这似乎很浪费。 这是否更快? qs = MyModel.objects.filter(blah = blah) if len(qs) > 0: return qs[0] else: return None

Good ways to sort a queryset?

what I'm trying to do is this: get the 30 Authors with highest score ( Author.objects.order_by('-score')[:30] ) order the authors by last_name Any suggestions? What about import operator auths = Author.objects.order_by('-score')[:30] ordered = sorted(auths, key=operator.attrgetter('last_name')) In Django 1.4 and newer you can order by providing multiple fields. Reference:

排序查询集的好方法?

我想要做的是这样的: 获得最高分数的30位作者( Author.objects.order_by('-score')[:30] ) 以last_name命令作者 有什么建议么? 关于什么 import operator auths = Author.objects.order_by('-score')[:30] ordered = sorted(auths, key=operator.attrgetter('last_name')) 在Django 1.4和更新版本中,您可以通过提供多个字段进行排序。 参考:https://docs.djangoproject.com/en/dev/ref/models/query

In Django, how does one filter a QuerySet with dynamic field lookups?

Given a class: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.fo

在Django中,如何使用动态字段查找过滤QuerySet?

给定一个类: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) 是否有可能,如果是这样,有一个基于动态参数的过滤器的QuerySet? 例如: # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_v

.update(…) with an extra(…) and F(…)

I want to do one sql query to update a lot of models in a Django site. I want to change one char column/field to be based on the id and some text, in MySQL (which this site is), I'd do that with "UPDATE table SET blah = 'prefix'||id||'suffix'" . My first attempt of doing this in Django was: Model.objects.update(blah='prefix'+F('id')+'suffix') But that tries to g

.update(...)带有额外的(...)和F(...)

我想做一个sql查询来更新Django站点中的很多模型。 我想改变一个字符列/字段是基于id和一些文本,在MySQL(这是该网站是),我会这样做"UPDATE table SET blah = 'prefix'||id||'suffix'" 。 我在Django做这件事的第一次尝试是: Model.objects.update(blah='prefix'+F('id')+'suffix') 但是,这试图给MySQL一个+ ,而不是|| 运营商。 我的下一个尝试是使用.extra(…)像这样: Model.objects.e

Select between two dates with Django

I am looking to make a query that selects between dates with Django. I know how to do this with raw SQL pretty easily, but how could this be achieved using the Django ORM? This is where I want to add the between dates of 30 days in my query: start_date = datetime.datetime.now() + datetime.timedelta(-30) context[self.varname] = self.model._default_manager.filter( current_issue__isnull=Tru

用Django选择两个日期

我正在寻找使用Django在日期之间进行选择的查询。 我知道如何用原始SQL很容易地做到这一点,但如何使用Django ORM实现这一点? 这是我想在查询中添加30天之间的日期: start_date = datetime.datetime.now() + datetime.timedelta(-30) context[self.varname] = self.model._default_manager.filter( current_issue__isnull=True ).live().order_by('-created_at') 使用__range运算符: ...filter(current_issue__is

Matching only some words in query using Django Haystack

I am currently using the following django-haystack code to do searches on my site: def products_search_results(request): q = request.GET['q'] from haystack.query import SearchQuerySet products = SearchQuerySet().models(Product).filter(text=q) This uses q as the query parameter in the search. This is also using all words in q to match the results against. This is probably (?) the i

只使用Django Haystack在查询中匹配一些单词

我目前使用下面的django-haystack代码在我的网站上进行搜索: def products_search_results(request): q = request.GET['q'] from haystack.query import SearchQuerySet products = SearchQuerySet().models(Product).filter(text=q) 这在搜索中使用q作为查询参数。 这也是使用q中的所有单词来匹配结果。 这可能是(?)预期的默认行为。 这是我所看到的。 我有一个Product与“红色克尔维特”的称号。 当然

iregex to match complete word only

So I've been trying to implement a search feature where by a user can enter a keyword and look up users. The search method is supposed to look up exact word matches within the fields of the users eg first name, last name, job etc I have tried icontains but that would also match within the words eg if the user enters 'a' the search would return anything that contains an 'a'.

iregex只匹配完整的单词

所以我一直在试图实现一个搜索功能,用户可以输入关键字并查找用户。 搜索方法应该在用户的字段中查找精确的单词匹配,例如名字,姓氏,工作等 我已经尝试过图标,但是也会在单词内匹配,例如,如果用户输入“a”,搜索将返回包含“a”的任何内容。 (在我决定解决这个问题之前,这正是我原先所做的) 我试过iexact但显然会给出完全匹配,如果用户输入'john',则会跳过名字为'john doe'或其他用户的用户。

Getting the SQL from a Django QuerySet

This question already has an answer here: How can I see the raw SQL queries Django is running? 11 answers 您打印query的query属性。 >>> queryset = MyModel.objects.all() >>> print queryset.query SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel" Easy: print my_queryset.query For example: from django.contrib.auth.models import User print User.objects.filter(last_name__ic

从Django QuerySet获取SQL

这个问题在这里已经有了答案: 我怎样才能看到Django正在运行的原始SQL查询? 11个答案 您打印query的query属性。 >>> queryset = MyModel.objects.all() >>> print queryset.query SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel" 简单: print my_queryset.query 例如: from django.contrib.auth.models import User print User.objects.filter(last_name__icontains = 'ax').query 还应

How to expose some specific fields of model

I want to create a ModelForm which gonna show some specific field of ControlInstruction if device_type of Device is equals DC . Otherwise show all fields. Suppose, if device type == 'DC': show these filed in form-> on_off_flag, speed_flag, direction_flag else: show all How can I do that? class Device(models.Model): DEVICE_TYPES = ( ('AC', 'AC MOTOR'),

如何揭示模型的某些特定领域

我想创建一个ModelForm ,如果device的device_type是等于DC ,它将显示ControlInstruction某个特定字段。 否则显示所有字段。 Suppose, if device type == 'DC': show these filed in form-> on_off_flag, speed_flag, direction_flag else: show all 我怎样才能做到这一点? class Device(models.Model): DEVICE_TYPES = ( ('AC', 'AC MOTOR'), ('DC', 'DC MOTOR'),