Darkness
Darkness

Reputation: 165

Find the difference between two model field

I want to find the difference between quantity of Product class and sold_quantity of Stock class. How do I do that

models.py

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)
    quantity = models.IntegerField(null=True, blank=True)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.name


class Stock(models.Model):
    sold_quantity = models.IntegerField(null=True, blank=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.product.name

Upvotes: 0

Views: 55

Answers (1)

Lewis
Lewis

Reputation: 2798

For one instance you can do this by:

Example: id=1

product_instance = Product.objects.get(id=1)
quantity_difference = product_instance.quantity - product_instance.stock.sold_quantity

Note: This assumes the relationship is coupled between models.

Upvotes: 1

Related Questions