Search code examples
djangodjango-modelsgeneric-relationship

How can I retrieve all items associated with a model using a generic relation?


I am making a small browser-based game while trying to learn Django. I have many models which can all have "Items" associated with them.

Here is one of the models that can contain items:

class Bank(models.Model):
    user = models.ForeignKey(User, unique=True)
    cash = models.IntegerField()

My Item class has a generic relation so it can be associated with any of my models that need to contain items. It also has a ForeignKey to a user since each item must be owned by a user:

class Items(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    description = models.TextField()
    itemType = models.CharField(max_length=50)
    stats = models.CommaSeparatedIntegerField(max_length=100)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

My question is how can I get a list of items that are currently associated with a Bank(or any of my other models that can have items)?

Is using a generic relation a good way to do this? Would it be easier (or even possible) to do something like this using a ManyToMany relationship instead?

I would like to avoid using an actual GenericRelation field in my models that can have items as that would delete the model if I deleted the item. The idea is that the items are temporary but the models that have items are permanent.

Thanks for taking the time to read and answer!


Solution

  • To access your Items from a Bank easily you can provide a shortcut in your model:

    class Bank(models.Model):
        ...
        items = generic.GenericRelation(Item)
    

    Note that this is just a shortcut for django to know what to look for. If you delete your Bank your Items won't be affected.