简体   繁体   English

将模型添加到特定用户(Django)

[英]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? 我曾考虑过通过ForeignKey将User Object本身添加到项目的模型中,但是最后是否不必筛选所有条目以查找附加到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? 有什么更好的解决方案?

From what I understand of your use case, a User can have many items and and an Item can belong to multiple users. 据我对您的用例的了解,一个User可以有多个项目,而一个Item可以属于多个用户。 It this s the case, using ManyToManyField seems the way to go : 就是这种情况,使用ManyToManyField似乎是ManyToManyField的方法:

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: 要创建UserItem的绑定对象,只需实例化中间模型:

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

    assert user in item.users.all()

You could create a model UserItems for each user with a ForeignKey pointing to the user and an item ID pointing to items. 您可以为每个用户创建一个UserItems模型,其中ForeignKey指向该用户,Item ID指向项目。 The UserItems model should store the unique item IDs of the items that belong to a user. UserItems模型应存储属于用户的项目的唯一项目ID。 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. 如果项目可以附加到多个用户,或者可以存在尚未附加到任何用户的项目,则此方法应该更好地扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM