Home > Enterprise >  Django Many to Many - polymorphic
Django Many to Many - polymorphic

Time:01-27

In a Django application, I have three models:

  • Service
  • Product
  • AppliedTax

I want to create a many-to-many relationship between Service and AppliedTax and between Product and AppliedTax. Normally I would have an intermediate model (i.e. AppliedTaxTaxable) with three fields (applied_tax_id, taxable_type and taxable_id) and taxable_type taxable_id would be a composite foreign key for each related model with taxable_type having as value the name of the related model (Service or Product in my case) and the taxable_id field the id of the related record of the respective model.

I understand how to make it work with raw queries, but Is there a "Django" way to do that with a ManyToMany relationship? So far I had no luck with that. I don't have much experience with Django, but I hope there is a way to do that without using raw queries.

Help :)

CodePudding user response:

Well, after some thought, I did a better search and stumbled upon django-polymorphic. Here is a pretty straightforward explanation on how it works, for a basic set up and it does what I am describing in my question. The implemented schema differs a bit from what my description, but in the end we will home one intermediate table for all associated models.

CodePudding user response:

It's very easy:

In your Service model:

class Service(model.Model):
   ...
   ...
   taxes = ManyToManyField("AppliedTax")

In your Product model:

class Product(model.Model):
   ...
   ...
   taxes = ManyToManyField("AppliedTax")

Then using is very simple too:

product.taxes.add(<AppliedTax instance>)

Selecting:

product.taxes.all()

Filtering:

product.taxes.filter(is_vat=True) # you can filter by AppliedTax's fields.

More docs are here

  •  Tags:  
  • Related