0

I have the following model structure. Is it possible to alter the InventoryManager to check if a loaf is no longer in inventory due to having been sliced up?

from django.db import models
from shipping.models import Shipment


class InventoryManager(models.Manager):
    def get_queryset(self):
        # BUG: Does not check if BreadSlices are shipped
        return super(InventoryManager, self).get_queryset().filter(
            shipment__isnull=True, )


class BreadLoaf(models.Model):
    shipment = models.ForeignKey(Shipment, null=True, blank=True, )
    ...

    objects = models.Manager()
    inventory = InventoryManager()

    def get_shipment(self):
        if self.breadslice_set.all().exists():
            #  BUG: Returns duplicates
            return [bs.shipment for bs in self.breadslice_set.all()]
        else:
            return [self.shipment]


class BreadSlice(models.Model):
    loaf = models.ForeignKey(BreadLoaf)
    shipment = models.ForeignKey(Shipment, null=True, blank=True, )
    ...

I was hoping to use the get_shipment method, but it is not a field. I tried the following without success

class InventoryManager(models.Manager):
    def get_queryset(self):
        return super(InventoryManager, self).get_queryset().filter(
            shipment__isnull=True,
            breadslice_set.shipment_isnull=True, )

Thanks for reading!

Joost VanDorp
  • 348
  • 1
  • 2
  • 10

1 Answers1

0

Solution:

class InventoryManager(models.Manager):
    def get_queryset(self):
        return super(InventoryManager, self).get_queryset().filter(
            shipment__isnull=True,
            breadslice__shipment__isnull=True, )

Works.

BreadLoaf.inventory.all() # Returns all loaf of bread still in inventory.

https://docs.djangoproject.com/en/1.6/topics/db/queries/#lookups-that-span-relationships

Joost VanDorp
  • 348
  • 1
  • 2
  • 10