Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To do exactly what you're describing:</p> <blockquote> <p>I am trying to create a database relationship where CarMaunfacturer has many VehicleNames and also TruckManufacturer has many VehicleNames</p> </blockquote> <p>You'd create a nullable foreign key on VehicleName to both of your Manufacturer models:</p> <pre><code>class CarManufacturer(models.Model): # field definitions here class TruckManufacturer(models.Model): # field definitions here class VehicleName(models.Model): car_manufacturer = models.ForeignKey(CarManufacturer, blank=True, null=True) truck_manufacturer = models.ForeignKey(TruckManufacturer, blank=True, null=True) </code></pre> <p>Then, instances of <code>CarManufacturer</code> or <code>TruckManufacturer</code> can get the names via the <code>vehiclename_set</code> attribute.</p> <p>For a more advanced design, I would probably try to abstract the shared manufacturer behavior into a single model, then use multi-table inheritance:</p> <pre><code>class Manufacturer(models.Model): # shared car and truck manufacturer fields go here class CarManufacturer(Manufacturer): # car manufacturer specific fields go here class TruckManufacturer(Manufacturer): # truck manufacturer specific fields go here class VehicleName(models.Model): manufacturer = models.ForeignKey(Manufacturer) </code></pre> <p>See the <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance" rel="nofollow">multi-table inheritance docs</a> for full details.</p>
 

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