0
調用模型的方法,我很新的django
所以我的問題似乎很瑣碎.. 我有2款(簡化了演示目的):從另一個模型
class Subarticle(models.Model):
parent_article = models.ForeignKey(Article, related_name='subarticles')
priority = IntegerField()
....
def getCheapest(self, quantity): //find cheapest subarticle based on qty
//code
和
class Article(models.Model):
sub_article_qty = models.IntegerField()
def production_cost(self):
sub_article = Subarticle.objects.filter(parent_article=self).order_by('priority').first
sub_article_price = sub_article.getCheapest(self.sub_article_qty)
return sub_article_price*self.sub_article_qty
因此,基本上每篇文章都有一個或多個子文章,我希望能夠根據最低優先級編號的最便宜的子文章找到文章的成本。
我使用「rest_framwork
」與約以下serializer
from .models import Subarticles, Articles
from rest_framwork import serializers
class SubarticleSerializer(serializer.HyperlinkedModelSerializer):
class Meta:
model=Subarticle
fields=('parent_article','priority')
class ArticleSerializer(serializer.HyperlinkedModelSerializer):
class Meta:
model=Article
fields=('sub_article_qty','subarticles','production_cost')
但試圖做到這一點像這給了我下面的錯誤發送模型數據:
Exception raised in callable attribute "production_cost"; original exception was: 'function' object has no attribute 'getCheapest'
它甚至有可能按照我正在嘗試做的那樣去做,還是有其他一些方法來實現這一點?