【发布时间】:2015-03-12 06:41:00
【问题描述】:
所以我正在开发一个小型 Django 项目,目前不需要优化。但是为了为未来做准备,我想多了解一下这三种方法。
例如,作为模型的一部分,我有 User 和 UserProfile、Transaction。
class User(models.Model):
name = ...
email = ...
class UserProfile(models.Model):
user = models.ForeignKey(User, related_name='profile')
photo = models.URLField(...)
...
class Transaction(models.Model):
giver = models.ForeignKey(User, related_name="transactions_as_giver")
receiver = models.ForeignKey(User, related_name='transactions_as_receiver')
...
我经常需要执行类似“返回transactionsrequest.user 是giver 或receiver”之类的操作,或者“返回用户的个人资料照片”。我有几种选择,例如获取待处理交易列表和双方的photos,我可以在views.py 级别进行:
1.
#views.py
transactions = Transaction.objects.filter(Q(giver=request.user)|Q(receiver=request.user))
for transaction in transactions:
giver_photo = transactions.giver.profile.all()[0].photo
# or first query UserProfile by
# giver_profile = UserProfile.objects.get(user=transaction.giver),
# then giver_photo = giver_profile.photo
#
# Then same thing for receiver_photo
transaction['giver_photo'] = giver_photo
...
-
或者我可以在
template级别上做更多:# some template <!-- First receive transactions from views.py without photo data --> {% for t in transactions %} {{t.giver.profile.all.0.photo}}, ... {% endfor %} -
或者我可以将上述部分甚至全部内容移至
filters.py# some template {{ for t in request.user|pending_transactions }} {{ t.giver|photo }} {{ t.receiver|photo }} {{ endfor }}
其中photo 和pending_transactions 与原始views.py 中的代码大致相同,但已移至过滤器。
所以我想知道是否有关于如何选择哪种方法的最佳实践/指南?
从 Django 文档来看,低级别更快,因此 2. 3. 应该比 1 慢;但是比较 2. 和 3. 怎么样?
在获取用户照片时,应该推荐两者中的哪一个,transactions.giver.profile.all()[0].photo OR profile = UserProfile.objects.get(...) --> photo = profile.photo?
【问题讨论】:
标签: django django-models django-templates django-template-filters