Search code examples
pythondjangodjango-modelsdjango-rest-framework

Django: how to create a unique instance of one model as a field in another model


I am trying to store an instance of an Item model as a field in my users model using ForeignKey like so:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    username = models.CharField(max_length=255)
    items = models.ForeignKey('Item', on_delete=models.CASCADE)

    def __str__(self):
        return self.username
    
class Item(models.Model):
    stats = models.JSONField(null=True)
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

However, it currently seems that every new user is sharing the same list of items when I check my Django admin panel (essentially, there currently exists only one Item instance that is shared by every user). Instead, my goal is to have each user have their own list of items, unrelated to other users' list. Is there a way to make each user have a field in their account that is a unique instance of the Items model?


Solution

  • Your ForeignKey is in the wrong direction. A foreign key is a many-to-one relation, therefore your existing model structure implies "many UserProfiles to one Item".

    It should be in the Item model:

    class Item(models.Model):
        user_profile = models.ForeignKey(
            UserProfile, on_delete=models.CASCADE, related_name="items"
        )
        ...
    

    A ForeignKey field name should always be singular, and the related_name (i.e. the reverse relation) should be plural, so that both my_user_profile.items and my_item.user_profile make sense.