Django保存到ManyToMany字段 [英] Django saving to ManyToMany fields

查看:145
本文介绍了Django保存到ManyToMany字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型类,有2个ManyToManyField字段,如下所示:



models.py

 类文件夹(models.Model):
user = models.ManyToManyField(User)
asset = models.ManyToManyField(Asset)

在我看来,我知道用户ID和资产ID。说用户ID为1,资产ID为30,如何注入该行?我想我不明白如何实例化文件夹,以便我可以保存/更新行。



views.py

  def addAssetToMyFolder(request,id = None):
'''简化简化
'''
f =文件夹(
user = 1,
asset = 30,

f.save()


解决方案

将用户或资产实例与需要先保存文件夹的文件夹相关联。



为了存储多对多关系,数据库创建一个存储对象的id的第三个表。



所以如果你想关联一个用户到一个文件夹作为一个多对多的关系,他们都应该有自己的ids之前,他们可以相关多少。



说你有两个用户分别为10和19。
您有一个文件夹为id 4,用户10和用户19与此文件夹相关。在db级别,这些关系将如何存储

  folder_id user_id 
4 10
4 19

所以对于每个很多关系,两个模型的关系表中有一行。 p>

相同的对资产有效。



所以代码应该改为:

  def addAssetToMyFolder(request,id = None):
'''简化简化
'''
f = Folder()
f.save()
user = User.objects.get(id = 1)#如果添加id,则不需要
f.user.add(user)#或f.user.add(user_id)
asset = Asset.objects.get(id = 30)#如果添加id,则不需要
f.asset.add(asset)#或f.asset.add (asset_id)

查看: https://docs.djangoproject .com / en / 1.6 / topics / db / examples / many_to_many /


I have a simple model class with 2 ManyToManyField fields like this:

models.py

class Folder(models.Model):
    user = models.ManyToManyField(User)
    asset = models.ManyToManyField(Asset)

In my view, I know the user ID and the asset ID. Say the user ID is 1 and the asset ID is 30, how do I inject this row? I guess I don't understand how to instantiate Folder so I can save/update the row.

views.py

def addAssetToMyFolder(request, id=None):
    ''' view is simplified for brevity
    '''
    f = Folder(
        user = 1,
        asset = 30,
    )
    f.save()

解决方案

To associate a user or asset instance with a folder you need to first save the folder.

To store a many to many relationship the database creates a third table which stores the ids of the objects.

So if you want to relate a user to a folder as a many to many relationship, both of them should have their own ids before they can be related as many to many.

Say you have two users with ids 10 and 19 respectively. You have one folder with id 4 and user 10 and user 19 are related to this folder. At the db level this how these relations will be stored

   folder_id       user_id
       4            10
       4            19

so for each many to many relation there is one row in the relations table for the two models.

Same will be valid for asset.

So the code should be changed to:

def addAssetToMyFolder(request, id=None):
    ''' view is simplified for brevity
    '''
    f = Folder()
    f.save()
    user = User.objects.get(id=1)  # not needed if adding by id
    f.user.add(user)  # or f.user.add(user_id)
    asset = Asset.objects.get(id=30)  # not needed if adding by id
    f.asset.add(asset)  # or f.asset.add(asset_id)

check out : https://docs.djangoproject.com/en/1.6/topics/db/examples/many_to_many/

这篇关于Django保存到ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆