Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to connect different Product-objects to one Contract?
    primarykey
    data
    text
    <p><strong>My problem</strong>:<br> I want my Customers to be able to connect many different Products to one Contract, and the code to list all Products attached to a Contract feels dirty. </p> <p><strong>My Models</strong> </p> <pre><code>class Contract(models.Model): # The contract, a customer can have many contracts customer = models.ForeignKey(Customer) class Product(models.Model): # A contract can have many different products contract = models.ForeignKey(Contract) start_fee = models.PositiveIntegerField() # A customer may have ordered a Car, a Book and a HouseCleaning, # 3 completly different Products class Car(Product): brand = models.CharField(max_length=32) class Book(Product): author = models.ForeignKey(Author) class HouseCleaning(Product): address = models.TextField() </code></pre> <p>To list all the products connected to a Contract, the code looks something like this:</p> <pre><code>c = Contract.objects.get(pk=1) for product in c.product_set.all(): print product.book # Will raise an Exception if this product isnt a Book </code></pre> <p>I can't find any sane way to find out what kind of product a Product is!</p> <p><strong>My current solution</strong><br> I've solved it like this... but this whole mess feels... wrong. I'd be happy for any pointers in the right direction.</p> <pre><code>class Product(models.Model): # (as above + this method) def getit(self): current_module = sys.modules[__name__] classes = [ obj for name, obj in inspect.getmembers(current_module) if inspect.isclass(obj) and Product in obj.__bases__ ] for prodclass in classes: classname = prodclass.__name__.lower() if hasattr(self, classname): return getattr(self, classname) raise Exception("No subproduct attached to Product") </code></pre> <p>So i can fetch each specific product like this (pseudo-ish code) :</p> <pre><code>c = Contract.objects.get(pk=1) for product in c.product_set.all(): print product.getit() </code></pre> <p>to list all the "real" products, and not just the baseproduct instance.</p> <p><strong>What I need help with</strong><br> Sugggestions to do this in some kind of sane way.<br> I don't mind having to abstract everything away a bunch of steps, just to get cleaner code.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload