2👍
✅
You could implement the method in either class in the following manner:
NOTE: My assumption here is that it’s a 1-M relationship:
class Product(models.Model):
person = ForeignKey(Person)
...
def get_score(self):
# do your thing here
# use a person reference
if self.person:
# calculate score in one way
else:
# calculate score some other way
return score
OR you could implement it in the Person
class. It all depends on whether you want to work from the Person’s perspective or from the Product’s perspective
What you are proposing with Product.objects.get_score()
is for when you are performing the calculation over the entire queryset as opposed to a single item.
UPDATE: After clarification that product is not related to Person
In that case you can simply implement it as
class Product(models.Model):
...
def get_score(self, person):
# check the conditions you need to calculate the score
if person.has_some_property and self.has_some_product_property:
# calculate score in one way
else:
# calculate score some other way
return score
using the product instance you could then simply do:
person = Person.objects.get(pk=<some_id>)
product = Product.objects.get(pk=<some_id>)
product.get_score(person)
Source:stackexchange.com