Home > OS >  Calculating values from different Django Models
Calculating values from different Django Models

Time:12-17

I have 2 similar django models, the difference between them is that one of them has a Foreign key with another model and the other is like a general Model.

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")

I want to calculate the value attribute from Article model, it should be like this:

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

How should I do this type of calculations? Should I write the logic in views.py?

views.py:

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

In the template I use {% for article in projects.article_set.all %} to generate a table that has all the attributes as headers.

CodePudding user response:

ok based on your understanding you can do this way

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

Since you can access your clean method anywhere as it is instance of class in views

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 
  • Related