Ilya Bibik
Ilya Bibik

Reputation: 4124

accessing models in other apps from calculated field in django

I am trying to add a calculated field into my Material model to calculate my on hand inventory

for this i am trying to acces models located in 3 other apps: apps inventory, sales and purchase.

Instead of importing I use the app name as object. I can not import it because cross importing is not allowed.

But I am always getting error that - global name 'inventory' is not defined.

What am I doing wrong? Can I do it like this in general ?

@with_author  
class Material(models.Model):
    version = IntegerVersionField( )
    code = models.CharField(max_length=30)
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=80, blank=True)
    description = models.TextField(null=True, blank=True)
    materialuom = models.CharField(max_length=1,
                              choices=UOM_CHOICES)
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    itemgroup = models.ForeignKey(ItemGroup, on_delete=models.PROTECT)
    keywords = models.CharField(max_length=50,null=True, blank=True)
    valid_from = models.DateTimeField(null=True, blank=True)
    valid_to = models.DateTimeField(null=True, blank=True)
    min_quantity = models.DecimalField(max_digits=19, decimal_places=10)
    trigger_quantity = models.DecimalField(max_digits=19, decimal_places=10)
    max_quantity = models.DecimalField(max_digits=19, decimal_places=10)
    active = models.BooleanField(default=True)
    is_production = models.BooleanField(default=True)


    def _get_total(self):
    #    "Returns the total"

       return inventory.Inventory.objects.filter(material_id=self.id ).aggregate(Sum('quantity')) + purchase.PO.objects.filter(material_id=self.id).aggregate(Sum('quantity')) - sales.SO.objects.filter(material_id=self.id ).aggregate(Sum('quantity')) 


    total = property(_get_total)

Upvotes: 0

Views: 62

Answers (1)

Nick Hargreaves
Nick Hargreaves

Reputation: 436

You can try to import the required models locally in the _get_total function.

Upvotes: 1

Related Questions