Django:使用queryset值显示选项

2024-10-02 12:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在模板上使用get_status_display,它来自一个只包含模型中一些字段的查询集。在

我有一个带有选择字段(状态)的模型。在

class Operation(models.Model, ModelMixin):
    operation_area = models.ForeignKey('operations.OperationArea', null=True)

    created = models.DateTimeField(auto_now=True)
    indication = models.NullBooleanField()
    observation = models.TextField(blank=True, null=True)
    rate = models.IntegerField(blank=True, null=True)
    scheduling = models.DateTimeField(blank=True, null=True)
    status = models.IntegerField(choices=OPERATION_TYPE)

class OperationArea(models.Model, ModelMixin):
    campaign = models.ForeignKey('campaigns.Campaign')
    person = models.ForeignKey('registrations.Person')
    user = models.ForeignKey('authentication.User')

    area = models.CharField(max_length=1, choices=OPERATION_AREA)

我的问题是:

^{pr2}$

从这里得到一个get a dict,但是get_FOO_dislpay是一个实例方法,不适用于dict。我不想使用.only(),因为他带来了操作区域对象,并获得人名他又问了一句手术区.人名。有什么想法,如何使用一个查询和得到邱福龙显示?在


Tags: 模型truegetmodelmodelsstatusareanull
1条回答
网友
1楼 · 发布于 2024-10-02 12:31:30

我认为annotate()正是您所需要的。在

Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or an aggregate expression (averages, sums, etc.) that has been computed over the objects that are related to the objects in the QuerySet.

Each argument to annotate() is an annotation that will be added to each object in the QuerySet that is returned.

The aggregation functions that are provided by Django are described in Aggregation Functions below.

Annotations specified using keyword arguments will use the keyword as the alias for the annotation. Anonymous arguments will have an alias generated for them based upon the name of the aggregate function and the model field that is being aggregated. Only aggregate expressions that reference a single field can be anonymous arguments. Everything else must be a keyword argument.

您应该使用:

operations.annotate(person_name=F('operation_area__person__name')) 

看看https://docs.djangoproject.com/en/2.0/ref/models/querysets/#annotate。在

相关问题 更多 >

    热门问题