django - Where to add a method for a model? -
i have next scenario , i'm wondering best way implement within django:
i have 2 models product , person. want give score if product right person. question not how calculate within django?
i've been thinking have this…
product.object.getscore(person) or person.object.getscore(product)
so how in models got doing (forget actual scoring, thats not question)? set method , how in model? don't want store score, has dynamic based on object passed.
thanks.
you implement method in either class in next manner:
note: assumption here it's 1-m relationship:
class product(models.model): person = foreignkey(person) ... def get_score(self): # thing here # utilize person reference if self.person: # calculate score in 1 way else: # calculate score other way homecoming score
or implement in person
class. depends on whether want work person's perspective or product's perspective
what proposing product.objects.get_score()
when performing calculation on entire queryset opposed single item.
update: after clarification product not related person
in case can implement
class product(models.model): ... def get_score(self, person): # check conditions need calculate score if person.has_some_property , self.has_some_product_property: # calculate score in 1 way else: # calculate score other way homecoming score
using product instance do:
person = person.objects.get(pk=<some_id>) product = product.objects.get(pk=<some_id>) product.get_score(person)
django
No comments:
Post a Comment