您可以實現以下方式中任一類中的方法:
注:我在這裏的假設是,它是一個1-M的關係:
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
或者你可以實現它Person
類。這一切取決於您是想從人的角度還是從產品的角度來工作
您對Product.objects.get_score()
提出的建議是針對整個查詢集而不是單個項目執行計算。
UPDATE:澄清後該產品是不相關的人
在這種情況下,你可以使用該產品的情況下,你可以再簡單地實現它作爲
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
簡單地做:
person = Person.objects.get(pk=<some_id>)
product = Product.objects.get(pk=<some_id>)
product.get_score(person)
產品和人之間的關係是什麼? 1-1,1-M,M-M? – domino 2013-02-15 16:28:28
這取決於您是要計算任何模型的整個查詢集的分數,還是計算任一模型實例的屬性。 – Brandon 2013-02-15 16:36:11