简体   繁体   中英

Cost of Django many-to-many “through” relationship

If the foreign keys that define a many to many relationship are necessary anyway, is there any / much extra cost at the database level to telling Django that they define a many-to-many "through" relationship? Also, can a foreign key remain nullable in this circumstance?

What has to be there:

class StockLine( models.Model)              # a line of stock (ie a batch)

    # one or other of the following two is null depending on
    # whether Stockline was manufactured in-house or bought in.
    # (maybe both if it's been in stock "forever", no computer records)

    production_record = models.ForeignKey('ProductionRecord', 
          null=True, blank=True) 
    purchase_order = models.ForeignKey('PurchaseOrder', 
          null=True, blank=True) 

    itemdesc = models.ForeignKey('ItemDesc') 

    # other fields ...


class ItemDesc( models.Model)              # a description of an item
    # various fields

class ProductionRecord( models.Model)      # desc of a manufacturing process
    # various fields

There is an implied many-to-many relationship between ProductionRecord and ItemDesc through StockLine. Given that one of the foreign keys is nullable, can I make the M2M explicit by adding

class ItemDesc( models.Model) 
    production_records = models.ManyToManyField(ProductionRecord, 
             through='StockLine')

and if I can, is there any added cost at the database level, or is this change purely at the Django ORM level? It's not an essential relationship to make explicit and it won't be heavily used, but it would certainly make programming easier.

There shouldn't be any problems with null able fields, because it just means that they can have null as a value, not that they have to. So they remain useable for many-to-many relationships.
Keep in mind the restrictions for intermediate model and you should be fine. On the database level, you'd get an extra table if you don't use an intermediate model as Django needs an extra table for many-to-many-relationships, while with the "through" argument it uses the intermediate model's table.
The SQL query shouldn't be affected (regarding performance).

Generally, I'd recommend having your models follow your projects real-life logic, so use the intermediate model if it's appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM