Reputation: 169
I have a class which has a foreign key relationship with another class. I need a methord that returns the no. of instances of the second class corresponding to a particular instance of the first class
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
For Instance, I need a methord that returns the no. of Choices to a given Question
Upvotes: 0
Views: 38
Reputation: 570
Something like this (take a look at the official Django docs about many-to-one relationships):
def num_of_choices(question):
return question.choice_set.count()
Upvotes: 1