Hi Hi
Hi Hi

Reputation: 376

Add models to specific user (Django)

Good evening, I am working on some little website for fun and want users to be able to add items to their accounts. What I am struggling with is coming up with a proper solution how to implement this properly.

I thought about adding the User Object itself to the item's model via ForeignKey but wouldn't it be necessary to filter through all entries in the end to find the elements attached to x user? While this would work, it seems quite inefficient, especially when the database has grown to some point. What would be a better solution?

Upvotes: 2

Views: 1617

Answers (2)

Agate
Agate

Reputation: 3232

From what I understand of your use case, a User can have many items and and an Item can belong to multiple users. It this s the case, using ManyToManyField seems the way to go :

class Item(models.Model):
    users = models.ManyToManyField('auth.User', related_name='items')

You can then query items from a specific user like this:

    # adding an item to a user
    user.items.add(my_item)

    # query user items
    user.items.all()
    user.items.filter(name__startswith='Hello')

If you want to store additional information about the relationship, such as the date were the item was linked to the user, you have to specifiy an explicit intermediate model:

    class Item(models.Model):
        users = models.ManyToManyField('auth.User', through='ItemUser', related_name='users')

    class ItemUser(models.Model):
        """Explicit intermediary model"""
        user = models.ForeignKey('auth.User')
        item = models.ForeignKey(Item)
        date_added = models.DateTimeField(auto_now_add=True)

To create the binding beetween a User and an Item, just instanciate the intermediate model:

    binding = ItemUser(user=user, item=item)
    binding.save()

    assert user in item.users.all()

Upvotes: 1

benbo
benbo

Reputation: 1528

You could create a model UserItems for each user with a ForeignKey pointing to the user and an item ID pointing to items. The UserItems model should store the unique item IDs of the items that belong to a user. This should scale better if items can be attached to multiple users or if items can exist that aren't attached to any user yet.

Upvotes: 0

Related Questions