简体   繁体   English

Django如何从视图中的另一个模型获取字段?

[英]Django How do you get field from another model in a view?

I think this question has been asked a few times already, however, the questions and their answers are not that clear. 我认为这个问题已经被问过几次了,但是问题和答案还不清楚。 If you can make the headline question or the example below to be clearer. 如果您可以使标题问题或以下示例更清楚。 Please do. 拜托

Example: I have an orchard, within my orchard I have fields of apple trees and these apple trees have apples. 示例:我有一个果园,在我的果园中,我有苹果树田,这些苹果树有苹果。 The question is using my models: 问题是使用我的模型:

  1. how do I get the number of apples in a given field ? 如何获得给定字段中的苹果数量
  2. total mass of all the apples produced in that given field ? 在该特定领域生产的所有苹果的总质量

Model 模型

class Field(models.Model):
   size = models.PositiveIntergerField()
   max_tree_number = models.PositiveIntergerField()

class Tree(models.Model):
   field = models.ForeignKey(Field)
   date_of_planting = models.datefield(editable=False)
   variety = models.CharField(max_length=200)

class Apple(models.Model):
   tree = models.ForeignKey(Tree)
   mass = models.PositiveIntergerField()

View 视图

class FieldView(generic.ListView):
   template = '[app_name]/index.html'

   def get_context_data(self, **kwargs):
       context = super(FieldView, self).get_context_data(**kwargs)
       context['tree_count'] = Field._meta.model_name
       context['mass'] = ???
       context['apple_count'] = ???

Thank you for your time 感谢您的时间

You can annotate your queryset with the number of apples and mass. 您可以用苹果的数量和质量注释您的查询集。

from django.db.models import Count, Sum

def get_queryset(self):
    queryset = super(FieldView, self).get_queryset()
    queryset = queryset.annotate(num_apples=Count('tree__apple'), apple_mass=Sum('tree__apple__mass'))
    return queryset

Then, when you loop through the queryset you can access the annotated fields. 然后,当您遍历查询集时,您可以访问带注释的字段。

{% for obj in object_list %}
  {{ obj.size }}, {{ obj.num_apples }}, {{ obj.apple_mass }}
{% endfor %}

Note that you haven't had to add anything to the context in get_context_data , so you might be able to remove it from your view. 请注意,您无需在get_context_data的上下文中添加任何内容,因此您可以将其从视图中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM