django-orm

Django ORM - mock values().filter() chain

荒凉一梦 提交于 2019-11-30 02:05:04
问题 I am trying to mock a chained call on the Djangos model.Manager() class. For now I want to mock the values() and filter() method. To test that I created a little test project: Create a virtual environment Run pip install django mock mock-django nose django-nose Create a project django-admin.py startproject mocktest Create an app manage.py startapp mockme Add django_nose and mocktest.mockme to INSTALLED_APPS (settings.py) Add TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' to settings.py To

Per-transaction isolation level in Django ORM

笑着哭i 提交于 2019-11-30 01:01:18
问题 Is it possible to set isolation level for custom transaction (but not with raw sql)? For example, something like: with transaction.commit_on_success(isolation='SERIALIZABLE'): bla 回答1: As far as I know, there's no way to temporarily change the transaction isolation level in Django for an existing database connection(s). However, you could setup another database connection(s) that mirrors your default database connection(s) but sets the transaction isolation level. e.g. in your settings.py:

How to force Django Admin to use select_related?

时光毁灭记忆、已成空白 提交于 2019-11-29 23:04:24
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? 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 foreign key's foreign key. Maybe this could be helpful to someone. class MyModelAdmin(admin.ModelAdmin): model =

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

廉价感情. 提交于 2019-11-29 22:05:00
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(<other filters>) users = ??? I would like ??? to filter out users who do not have reports associated with

Move a python / django object from a parent model to a child (subclass)

假装没事ソ 提交于 2019-11-29 21:10:39
问题 I am subclassing an existing model. I want many of the members of the parent class to now, instead, be members of the child class. For example, I have a model Swallow. Now, I am making EuropeanSwallow(Swallow) and AfricanSwallow(Swallow). I want to take some but not all Swallow objects make them either EuropeanSwallow or AfricanSwallow, depending on whether they are migratory. How can I move them? 回答1: I know this is much later, but I needed to do something similar and couldn't find much. I

How to perform OR condition in django queryset?

坚强是说给别人听的谎言 提交于 2019-11-29 19:14:28
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. Lakshman Prasad from django.db.models import Q User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True)) via Documentation hobs Because QuerySets implement the Python __or__ operator ( | ), or union, it just works. As you'd expect, the | binary operator returns a

Subtracting two annotated columns

我只是一个虾纸丫 提交于 2019-11-29 13:07:45
I need to be able to sort on the aggregate of two annotated columns So I'd like to do something like this: c = c.annotate(metric=Sum('results__metric')) c = c.annotate(metric_prior=Sum('results__metric_prior')) c = c.annotate(variance=F('metric')-F('metric_prior')) #doesn't work, for demonstrative purposes only and then: c = c.order_by('variance') Does anyone know how to accomplish something like the above? Actually, c = c.annotate(variance=F('metric')-F('metric_prior')) works as you would like it to starting with Django 1.8 . Moreover, you can also order by an expression, which means you can

Annotate (group) dates by month/year in Django

走远了吗. 提交于 2019-11-29 12:49:32
问题 Using the Django DateQuerySet I'm pulling related years for item objects from a Group query. >>> Group.objects.all().dates('item__date', 'year') [datetime.date(1990, 1, 1), datetime.date(1991, 1, 1), ...(remaining elements truncated)...'] Now I want to perform a count by distinct year on these dates. I thought this would work: >>> Group.objects.all().dates('item__date', 'year').annotate(Count('year')) FieldError: Cannot resolve keyword 'year' into field. But looks like I'm missing something.

Django ORM, sum of multiple columns

柔情痞子 提交于 2019-11-29 12:36:16
I have a question about how we can filter by SUM of multiple columns. Example: class Foo(models.Model): i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() And I need to filter objects where SUM of i1, i2, i3 is less then 200. I've tried achive it with: Foo.objects.agregate(i_sum=Sum(i1,i2,i3)).filter(i_sum__lt=200) # error Foo.objects.agregate(i_sum=Sum([i1,i2,i3])).filter(i_sum__lt=200) # error Thanks. You can use F() , and with annotation : Foo.objects.annotate(i_sum=F('i1') + F('i2')+ F('i3')).filter(i_sum=200) You can use extra Foo.objects.extra(where=["i1 +

Django __in lowercase

烈酒焚心 提交于 2019-11-29 12:25:18
I'm using django-taggit , which handles the attachment of tags to arbitrary content types. I imported a large tag list, which contains many uppercase words, as well as lowercase words. Now, I' trying to get objects of another class containing a set of tags, but I want to compare case insensitively. When I do this: Media.objects.filter(tags__name__in=['tag1', 'tag2']) objects containing e.g. the tag "Tag1" are not found, only those ones with "tag1" or "tag2". Is there any possibility in the django orm to do something like: Media.objects.filter(tags__name__iin=['tag1', 'tag2']) that acts like