I am creating these models. I want to put toy into bags.
class Bag(models.Model):
name = models.charField()
@classmethod
def calculate_total_weight(cls, bag_id):
total_weight = 0
toys_in_bag = Toy.objects.filter(bag_id=bag_id)
for toy in toys_in_bag:
total_weight += toy.weight
return total_weight
class Toy(models.Model):
bag = models.ForeignKey(Bag, on_delete=models.CASCADE)
weight = models.IntegerField()
So here’s the problem. Toy belongs to bags, so toy has a foreign key pointing to Bag, so class Bag
should be defined first. So when declearing class function calculate_total_weight
, class toy
is not available yet.
for this specific problem, after searching I got a workaround: apps.get_model
from django.apps import apps
toy = apps.get_model('santa_gift','Toy')
but for other senario, how to tackle this issue?