Is it possible to link multiple models to one fiel in django?

Let's say I have these models:

class Material(models.Model):
    name = models.CharField([...])

class Consumable(models.Model):
    name = models.CharField([...])
    restores = models.IntegerField([...])

class Weapon(models.Model):
    name = models.CharField([...])
    damage = models.IntegerField([...])

# And then I have an 'inventory', like this one:

class Inventory(models.Model):
    user = models.ForeignKey([...]) # to which user you want to link the item
    item = models.ForeignKey([...]]) # which item
    quantity = models.IntegerField([...]) # how many of it

I want to be able to have all Material, Consumable, and Weapon models listed in the 'item' field, so when you want to add an item as an inline, you would see all 3 models' objects. Something like

# instead of this
item = models.ForeignKey(Consumable) # which item

# want something like this
item = models.ForeignKey(Consumable and Material and Weapon) # which item
# this wouldn't work ofc...

Is there a way to collect all 3 of them and pass them to the 'item' field, without the need of restarting the server? (when making a "choices" list that queries from a model you must restart the server to see the newly added objects, I don't want that.)

I also want to stick to the built-in admin of Django since it provided everything I need for the past couple of months, but I am open to any ideas.

I could be wrong but I think you are making this more complex than it needs to be. Instead of doing separate classes for materials (type of material) and consumable (type of product), you can have that built in the last class as model field as category or bolean fields.

class Products(models.Model):
    material_type = 
    consumable = boolean for yes no or you can do multiple choice field

Then for items you can query the number of items based on material_type or consumable model fields (see query filters for for more).

all_items = Products.model.all()
consumable_items = Products.model.filter(your filter logic goes here)

Hope this helps!

Back to Top