user7120561
user7120561

Reputation:

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

Upvotes: 1

Views: 1893

Answers (1)

Alasdair
Alasdair

Reputation: 308809

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.

Upvotes: 2

Related Questions