Django:values_list()连接多个字段

时间:2021-08-28 21:27:46

I have a Person model and I am using a django form to edit another object with a foreign key to Person. The person model has first_name and last_name fields. I want to run a method to filter results for the drop down box of the foreign reference.

我有一个Person模型,我使用django表单编辑另一个带有外键的Person对象。人员模型具有first_name和last_name字段。我想运行一个方法来过滤外部引用的下拉框的结果。

I am trying to use values_list() to override the form field options (choices property) like so:

我试图使用values_list()来覆盖表单字段选项(choices属性),如下所示:

data.form.fields['person'].choices = GetPersons().values_list('id', 'first_name')

GetPersons() just filters the Person class like

GetPersons()只过滤Person类

return Person.objects.filter(id__gt=1000)`

for example, so I only get people I want to show up. How can I use values_list() to return the concatenation of first_name and last_name without having to return a dictionary and splitting everything manually?

例如,所以我只会找到我想要出现的人。如何使用values_list()返回first_name和last_name的串联,而不必返回字典并手动拆分所有内容?

3 个解决方案

#1


11  

I have in mind 2 sugestions for you:

我想到了2个sugestions:

  • First one is to concatenate fields in database with extra . For me is a dirty solutions but can run.
  • 第一个是将数据库中的字段与extra连接起来。对我来说是一个肮脏的解决方案但可以运行

Sample:

样品:

persons =  GetPersons().extra(select={'full_name': "concatenate( first, last) "} )
choices = persons.values_list('id', 'full_name')

and ...

和......

  • the second one use list comprehension:
  • 第二个使用列表理解:

Sample:

样品:

choices = [ ( p.id, '{0} {1}'.format( p.first, p.last ),) for p in GetPersons() ]

#2


5  

It sounds like the annotate() function got more flexible in Django 1.8. You can combine two fields with a Concat expression and then annotate the queryset with that expression.

听起来像anangate()函数在Django 1.8中变得更加灵活。您可以将两个字段与Concat表达式组合,然后使用该表达式注释查询集。

# Tested with Django 1.9.2
import sys

import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase
from django.db.models.functions import Concat, Value

NAME = 'udjango'


def main():
    setup()

    class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)

    syncdb(Person)

    Person.objects.create(first_name='Jimmy', last_name='Jones')
    Person.objects.create(first_name='Bob', last_name='Brown')

    print(Person.objects.annotate(
        full_name=Concat('first_name',
                         Value(' '),
                         'last_name')).values_list('id', 'full_name'))
    # >>> [(1, u'Jimmy Jones'), (2, u'Bob Brown')]


def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(
        DEBUG=True,
        DATABASES={
            DEFAULT_DB_ALIAS: {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': DB_FILE}},
        LOGGING={'version': 1,
                 'disable_existing_loggers': False,
                 'formatters': {
                    'debug': {
                        'format': '%(asctime)s[%(levelname)s]'
                                  '%(name)s.%(funcName)s(): %(message)s',
                        'datefmt': '%Y-%m-%d %H:%M:%S'}},
                 'handlers': {
                    'console': {
                        'level': 'DEBUG',
                        'class': 'logging.StreamHandler',
                        'formatter': 'debug'}},
                 'root': {
                    'handlers': ['console'],
                    'level': 'WARN'},
                 'loggers': {
                    "django.db": {"level": "WARN"}}})
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()
    original_new_func = ModelBase.__new__

    @staticmethod
    def patched_new(cls, name, bases, attrs):
        if 'Meta' not in attrs:
            class Meta:
                app_label = NAME
            attrs['Meta'] = Meta
        return original_new_func(cls, name, bases, attrs)
    ModelBase.__new__ = patched_new


def syncdb(model):
    """ Standard syncdb expects models to be in reliable locations.

    Based on https://github.com/django/django/blob/1.9.3
    /django/core/management/commands/migrate.py#L285
    """
    connection = connections[DEFAULT_DB_ALIAS]
    with connection.schema_editor() as editor:
        editor.create_model(model)

main()

#3


0  

Per: Is it possible to reference a property using Django's QuerySet.values_list?, avoiding values_list when not applicable, using a comprehension instead.

Per:是否可以使用Django的QuerySet.values_list?引用属性,在不适用时避免使用values_list,而是使用理解。

models.py:
class Person(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=64)
    def getPrintName(self):
        return self.last_name + ", " + self.first_name

views.py:
data.form.fields['person'].choices = [(person.id, person.getPrintName()) for person in GetPersons()]

#1


11  

I have in mind 2 sugestions for you:

我想到了2个sugestions:

  • First one is to concatenate fields in database with extra . For me is a dirty solutions but can run.
  • 第一个是将数据库中的字段与extra连接起来。对我来说是一个肮脏的解决方案但可以运行

Sample:

样品:

persons =  GetPersons().extra(select={'full_name': "concatenate( first, last) "} )
choices = persons.values_list('id', 'full_name')

and ...

和......

  • the second one use list comprehension:
  • 第二个使用列表理解:

Sample:

样品:

choices = [ ( p.id, '{0} {1}'.format( p.first, p.last ),) for p in GetPersons() ]

#2


5  

It sounds like the annotate() function got more flexible in Django 1.8. You can combine two fields with a Concat expression and then annotate the queryset with that expression.

听起来像anangate()函数在Django 1.8中变得更加灵活。您可以将两个字段与Concat表达式组合,然后使用该表达式注释查询集。

# Tested with Django 1.9.2
import sys

import django
from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import connections, models, DEFAULT_DB_ALIAS
from django.db.models.base import ModelBase
from django.db.models.functions import Concat, Value

NAME = 'udjango'


def main():
    setup()

    class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)

    syncdb(Person)

    Person.objects.create(first_name='Jimmy', last_name='Jones')
    Person.objects.create(first_name='Bob', last_name='Brown')

    print(Person.objects.annotate(
        full_name=Concat('first_name',
                         Value(' '),
                         'last_name')).values_list('id', 'full_name'))
    # >>> [(1, u'Jimmy Jones'), (2, u'Bob Brown')]


def setup():
    DB_FILE = NAME + '.db'
    with open(DB_FILE, 'w'):
        pass  # wipe the database
    settings.configure(
        DEBUG=True,
        DATABASES={
            DEFAULT_DB_ALIAS: {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': DB_FILE}},
        LOGGING={'version': 1,
                 'disable_existing_loggers': False,
                 'formatters': {
                    'debug': {
                        'format': '%(asctime)s[%(levelname)s]'
                                  '%(name)s.%(funcName)s(): %(message)s',
                        'datefmt': '%Y-%m-%d %H:%M:%S'}},
                 'handlers': {
                    'console': {
                        'level': 'DEBUG',
                        'class': 'logging.StreamHandler',
                        'formatter': 'debug'}},
                 'root': {
                    'handlers': ['console'],
                    'level': 'WARN'},
                 'loggers': {
                    "django.db": {"level": "WARN"}}})
    app_config = AppConfig(NAME, sys.modules['__main__'])
    apps.populate([app_config])
    django.setup()
    original_new_func = ModelBase.__new__

    @staticmethod
    def patched_new(cls, name, bases, attrs):
        if 'Meta' not in attrs:
            class Meta:
                app_label = NAME
            attrs['Meta'] = Meta
        return original_new_func(cls, name, bases, attrs)
    ModelBase.__new__ = patched_new


def syncdb(model):
    """ Standard syncdb expects models to be in reliable locations.

    Based on https://github.com/django/django/blob/1.9.3
    /django/core/management/commands/migrate.py#L285
    """
    connection = connections[DEFAULT_DB_ALIAS]
    with connection.schema_editor() as editor:
        editor.create_model(model)

main()

#3


0  

Per: Is it possible to reference a property using Django's QuerySet.values_list?, avoiding values_list when not applicable, using a comprehension instead.

Per:是否可以使用Django的QuerySet.values_list?引用属性,在不适用时避免使用values_list,而是使用理解。

models.py:
class Person(models.Model):
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=64)
    def getPrintName(self):
        return self.last_name + ", " + self.first_name

views.py:
data.form.fields['person'].choices = [(person.id, person.getPrintName()) for person in GetPersons()]