Hi from all round newbie.
New to this forum, new to Python and Django. Migrating from other languages.
Need some advice on how best to go about this...
I have a parent-child relationship. Country table linked to Provinces(States).
Would like to have the number of provinces shown when listing the Countries in a list view.
Thought to create a Method in the parent that would return this. Or is there an out of the box feature in Django that does this?
class Country(models.Model):
country_id = models.CharField(max_length=2)
country_name = models.CharField(max_length=35)
def __str__(self):
return self.country_id
def get_absolute_url(self):
return reverse('country-detail', kwargs={'pk':self.pk})
def get_child_count(self):
return Province.objects.filter(country_id=self.country_id)
class Province(models.Model):
province_id = models.CharField(max_length=2)
province_name = models.CharField(max_length=35)
country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='provinces')
def __str__(self):
return self.province_id
Thanks in advance.
question from:
https://stackoverflow.com/questions/66061654/django-class-based-models-how-to-create-a-method-to-return-number-of-children-in 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…