English 中文(简体)
Django QuerySets如何写别?
原标题:How to write alias in Django QuerySets?

How can one write an alias for the column name in django query set. Would be useful for union-style combinations of two linked field to the same foreign model (for instance).

例如,我sql:

select m as n, b as a from xyz

如何在集延戈问询中做到这一点?

models.Table.objects.all().values( m ,  b )

任何帮助都会真正得到赞赏。

问题回答

您可以按照你的愿望,用来说明这些领域。 F expression:

from django.db.models import F

models.Table.objects.all().values( m ,  b ).annotate(n=F( m ), a=F( b ))

虽然在此之前可以使用<代码>extra(select={ n : m , a :b },但我同意,这确实应当成为 Values()的一部分。

为此,在Alex s张票的启发下,我有上张贴了>>, 发送了,增加了这一特点。 我希望你们会认为它是有益的!

你在评论中的理由毫无意义。 该模型的每个领域都有自己的数据库一栏,从来都不会有混淆这些数据库的危险。 当然,你可以告诉一个领域,使用一个不同于外地名称的栏目:

myfield = models.CharField(max_length=10, db_column= differentname )

但我不知道这是否会帮助你,因为我仍然不知道你的问题是什么。

you also use .alias () in You queryset.

.alias(alias=SomeExpression()).annotate(                     
    SomeOtherExpression( alias ))
.alias(alias=SomeExpression()).order_by( alias )
.alias(alias=SomeExpression()).update(field=F( alias ))

具体来说,这是答案。

models.Table.objects.all().alias(
    n=F( m ), a=F( b )).values( m ,  a )
)

我确实能够理解你试图做些什么,就像你所期望的那样:ex 。 查询方法。 在大多数情况下,这种做法的行文方式与普通航程相同。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签