我正在创建一个举重数据库,或者也在尝试。我有一个用户深蹲,硬拉和卧推量。让我说我想添加硬拉和替补金额,例如,但不存储它,在mysql shell中我这样做:
mysql> SELECT sq, dl, bp, sq+dl AS sq_+_dlweight FROM mysite_weightsprofile
好的,我明白了。
在视图中,我可以这样做:
conn = mdb.connect('localhost', 'bobby', '#########', 'website');
cursor = conn.cursor()
cursor.execute("SELECT sq, dl, bp, sq+dl AS sq_+_dlweight FROM mysite_weightsprofile")
rows = cursor.fetchall()
然而,这种方法似乎相当有价值,很难适应模板而且不是很可调。有没有办法可以使用短代码
来完成上述操作query_results = UserProfile.objects.all("?")
无需创建游标对象。
答案 0 :(得分:0)
只需在模型中添加方法即可。例如:
class UserProfile(Model):
squats = IntegerField(null=True, blank=True)
deadlift = IntegerField(null=True, blank=True)
def squats_and_deadlifts(self):
return self.squats + self.deadlift
然后在你的模板中:
{% for user_profile in query_results %}
Deadlifts + squats: {{ user_profile.squats_and_deadlifts }}
{% endfor %}