django-orm

django - reorder queryset after slicing it

﹥>﹥吖頭↗ 提交于 2019-12-21 04:34:32
问题 I fetch the latest 5 rows from a Foo model which is ordered by a datetime field. qs = Foo.objects.all()[:5] In the following step, I want to reorder the queryset by some other criteria (actually, by the same datetime field in the opposite direction). But reordering after a slice is not permitted. reverse() undoes the first ordering, giving me a differet queryset. Is there a way to accomplish what I want without creating a list from the queryset and doing the ordering using it? 回答1: No, there

Django: get aggregated value of two multiplied columns

非 Y 不嫁゛ 提交于 2019-12-20 23:26:08
问题 I need to get aggregated value of two columns. So first multiple them together and then get theirs sum() . Code below naturally does not work, it is just for clarification. Is it somehow possible or should I use raw SQL? SomeModel.objects .filter(**something) .aggregate(Sum('one_column' * 'another_col')) 回答1: You don't need that much raw SQL using extra(). obj = SomeModel.objects.filter(**something).extra( select = {'total': 'SUM(one_column * another_column)'}, ) 回答2: As I answered here https

Django many-to-many model DRF

你。 提交于 2019-12-20 06:12:01
问题 I have the following model structure: class Project(models.Model): author = models.ManyToManyField(Account) name = models.CharField(max_length=40, default='NewBook') class Account(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40, blank=True) last_name = models.CharField(max_length=40, blank=True) tagline = models.CharField(max_length=140, blank=True) is_admin = models.BooleanField

Django complex annotation

扶醉桌前 提交于 2019-12-20 03:00:10
问题 Pre-requisites: Queryset must return Article s Queryset must return unique objects Must not utilize for loops that hit the database (meaning N queries for N objects to annotate) my models: class Report(BaseModel): ios_report = JSONField() android_report = JSONField() class Article(BaseModel): internal_id = models.IntegerField(unique=True) title = models.CharField(max_length=500) short_title = models.CharField(max_length=500) picture_url = models.URLField() published_date = models.DateField()

How to calculate if age is in range from the birth year ,while fetching the birth year from Db in Django ORM

馋奶兔 提交于 2019-12-19 10:21:49
问题 I have a model which consists of id, name and birth year.I want to query this model to get the name such that the age is in between a range. For now, what i have tried is queryset= Employees.objects.all() For each name i calculate the age by: now = datetime.datetime.now() age=now.year-q.birth_year ids=[] if 25<age<36 : ids.append(q.id) and then, i query once again with ids Employees.objects.filter(id__in=ids) Can i do all this in a single query. Employees.objects.filter(**Calculate age and

Migrations in stand alone Django app

☆樱花仙子☆ 提交于 2019-12-19 09:27:29
问题 How do I makemigrations on a stand alone Django app (ie one that is not part if any project). For example after following: https://docs.djangoproject.com/en/1.8/intro/reusable-apps/ 回答1: You can do it similar to how you do testing scripts for apps: #!/usr/bin/env python import sys import django from django.conf import settings from django.core.management import call_command settings.configure(DEBUG=True, INSTALLED_APPS=( 'django.contrib.contenttypes', 'your_app', ), ) django.setup() call

Postgres: values query on json key with django

折月煮酒 提交于 2019-12-18 21:12:07
问题 I need to do a values/values_list query on nested key on a postgres backed jsonfield in django 1.10 eg. class AbcModel(models.model): context = fields.JSONField() If it has values like: { 'lev1': { 'lev': 2 } } I want to run a queries like AbcModel.objects.values('context__lev1__lev2').distinct() AbcModel.objects.values_list('context__lev1__lev2', flat=True).distinct() EDIT: The JSON fields are the official django JSONField from django.contrib.postgres.fields 回答1: So I found a solution, this

How to filter django model by its objects in many-to-many field (exact match)?

陌路散爱 提交于 2019-12-18 19:01:20
问题 I have this model in my code: class Conversation(models.Model): participants = models.ManyToManyField(User, related_name="message_participants") and I need to filter this "Conversation" model objects by the "participants" many-to-many field. meaning: I have for example 3 User objects, so I want to retrieve the only "Conversation" objects that has this 3 Users in it's "participants" field. I tried doing this: def get_exist_conv_or_none(sender,recipients): conv = Conversation.objects.filter

Django and Aggregate: Sum of distinct values?

纵饮孤独 提交于 2019-12-18 13:15:32
问题 I am trying to do a django aggregate function, but am unable to produce the desired result. What I've got: income_posts.values_list('category__name','amount') [(u'Donation', Decimal("2000.00")), (u'Paycheck', Decimal("1200.00")), (u'Donation', Decimal("1000.00"))] Desired result: [(u'Donation', Decimal("3000.00")), (u'Paycheck', Decimal("1200.00))] I need to Sum the 'amount' fields that have the same category__name. 回答1: From this answer for a related question: from django.db.models import

Model in sub-directory via app_label?

99封情书 提交于 2019-12-18 12:18:23
问题 In order to place my models in sub-folders I tried to use the app_label Meta field as described here. My directory structure looks like this: project apps foo models __init__.py bar_model.py In bar_model.py I define my Model like this: from django.db import models class SomeModel(models.Model): field = models.TextField() class Meta: app_label = "foo" I can successfully import the model like so: from apps.foo.models.bar_model import SomeModel However, running: ./manage.py syncdb does not