Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django how to have multiple foreignkey from the same model

Here is my model:

class Item(models.Model):
    name = models.CharField(max_length=30)
    ...
    choices = (
        ('weapon', 'weapon'),
        ('shield', 'shield'),
    )
    typeOf = models.CharField(max_length=15, choices=choices)



class Character(models.Model):
    name = models.CharField(max_length=30, unique=True)
    ...
    weapon = models.ForeignKey(Inventory) // **THIS IS WHAT I WANT TO DE BUT DOES'NT WORK**
    shield = models.ForeignKey(Inventory) // **THIS IS WHAT I WANT TO DE BUT DOES'NT WORK**
    inventory = models.ManyToManyField(Item, through='Inventory')




class Inventory(models.Model):
    character = models.ForeignKey('Character')
    item = models.ForeignKey('Item')

I know how to add item to inventory but now I want to equip them. How do I do the foreign key? I want to be able to equip weapon from my inventory

like image 690
TotuDoum Avatar asked Dec 12 '22 01:12

TotuDoum


1 Answers

You need to add related_name to the field definition

...
weapon = models.ForeignKey(Inventory, related_name='weapons') 
shield = models.ForeignKey(Inventory, related_name='shields')
...

Without the related_name, django will try to create character_set attribute in Inventory model, but it will fail for 2nd.

like image 155
Rohan Avatar answered May 13 '23 16:05

Rohan