是否有最好的"做可以查询的计算字段的方法吗?
例如:
from django.db import models
class Person(models.Model):
given_name = models.CharField(max_length=30)
family_name = models.CharField(max_length=30)
NAME_ORDER_CONVENTION_CHOICES = (
# "Eastern" name order: family name followed by given name
('E', 'Eastern'),
# "Western" name order: given name followed by family name
('W', 'Western')
)
name_order_convention = models.CharField(
length=1,
choices=NAME_ORDER_CONVENTION_CHOICES,
)
@property
def full_name(self):
"""
Return full name, calculated on the basis of given name,
family name and name order convention.
"""
template = "{} {}"
if self.name_order_convention == "W":
return template.format(self.given_name, self.family_name)
return template.format(self.family_name, self.given_name)
这使您能够为任何full_name
获取Person
,但如果您想基于全名进行数据库查询,则需要编写一个隐含的如何知道查询的查询此属性是计算的。这似乎违反了DRY,因为不再有任何中心位置可以更改计算字段的计算方式 - 您必须更改full_name
属性,以及任何位置查询基于full_name
如何工作的隐含知识。
我能想到的主要替代方法是覆盖save()
方法以在每次更新时更新这些字段。
from django.db import models
class Person(models.Model):
given_name = models.CharField(max_length=30)
family_name = models.CharField(max_length=30)
NAME_ORDER_CONVENTION_CHOICES = (
('E', 'Eastern'),
('W', 'Western')
)
name_order_convention = models.CharField(
length=1,
choices=NAME_ORDER_CONVENTION_CHOICES,
)
# Computed fields
full_name = models.CharField(max_length=60)
def _calculate_full_name(self):
template = "{} {}"
if self.name_order_convention == "W":
self.full_name = template.format(self.given_name, self.family_name)
else:
self.full_name = template.format(self.family_name, self.given_name)
def save(self, *args, **kwargs):
self._calculate_full_name()
super(Model, self).save(*args, **kwargs)
是否有共同的,最好的做法"我可能会遗漏的可查询计算字段的解决方案?
答案 0 :(得分:2)
我可以看到的一种方式:在数据库中使用连接的full_name创建视图,而不是用于查询的django中的托管模型(Person
模型也应存在于crud操作中) :
view(postgresql)
CREATE OR REPLACE VIEW appname_viewperson AS
SELECT id,
given_name,
family_name,
given_name || ' ' || family_name AS full_name,
FROM appname_person
非管理型号:
class ViewPerson(models.Model):
given_name = models.CharField(max_length=30)
family_name = models.CharField(max_length=30)
full_name = models.CharField(max_length=60)
class Meta:
managed = False
答案 1 :(得分:0)
答案可能在于django相当新的查询注释:
https://docs.djangoproject.com/en/1.11/ref/models/expressions/#using-f-with-annotations
company = Company.objects.annotate(
chairs_needed=F('num_employees') - F('num_chairs'))