计算不同Django模型的值

cu6pst1q  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(110)

我有2个类似的django模型,它们之间的区别是其中一个有一个外键与另一个模型,另一个就像一个通用模型。

class Project: 
  name = models.CharField(default='',max_length=100,verbose_name="name")

class Article(models.Model):    
    code = models.CharField(default='',max_length=20,verbose_name="Norma")
    name = models.TextField(default='',verbose_name="Denumire")
    project = models.ForeignKey(Project,on_delete=models.CASCADE,null=True)
    quantity = models.FloatField(default=0,verbose_name="Quantity")
    value = models.FloatField(default=0,verbose_name="Value")

class BaseArticle(models.Model):
    code = models.CharField(default='',max_length=20,verbose_name="Norma")

    name = models.TextField(default='',verbose_name="Denumire")
    
    price = models.FloatField(default=0,verbose_name="Price")

我想从Article模型中计算value属性,应该是这样的:

if article.code == basearticle.code:
     article.value = article.quantiy * basearticle.price

我应该如何进行这种类型的计算?我应该在www.example.com中编写逻辑views.py?
views.py:

class ProjectDetail(LoginRequiredMixin, DetailView):   
    template_name = "proiecte/project_detail.html"
    context_object_name = "projects"
    model = Project

在模板中,我使用{% for article in projects.article_set.all %}来生成一个表,该表将所有属性作为表头。

xkrw2x1b

xkrw2x1b1#

好的根据你的理解你可以这样做

class Article(models.Model):    
    code = models.CharField(default='',max_length=20,verbose_name="Norma")
    name = models.TextField(default='',verbose_name="Denumire")
    project = models.ForeignKey(Project,on_delete=models.CASCADE,null=True)
    quantity = models.FloatField(default=0,verbose_name="Quantity")
    value = models.FloatField(default=0,verbose_name="Value")

    def clean(self):
        values =Article.objects.get(code='P1').quantity*BaseArticle.objects.get(code = 
        Article.objects.get(code='P1')
       return value

因为你可以在任何地方访问你的clean方法,因为它是视图中类的示例

class ProjectDetail(LoginRequiredMixin, DetailView):   
    template_name = "proiecte/project_detail.html"
    context_object_name = "projects"
    instance = Article.objects.get(pk=id)
    value =instance.clean()
    # your logic

相关问题