初学 python 对于 Django orm 中 add/remove relationship 的疑问

2015-04-03 15:22:12 +08:00
 cctecoo
class System(models.Model):
    users = models.ManyToManyField(User, db_table="system_user_relationships", related_name="belong_system")
    ...
class User(models.Model):
    ...

还有一个中间表:system_user_relationships

创建单条relationship的时候:

sy, created = System.objects.get_or_create(id=id)
u = User.objects.create(id=id)
sy.users.add(u)

1.那对于创建多条relationship是不是如下??

sy, created = System.objects.get_or_create(id=id)
u = User.objects.filter(id=id)
sy.users.add(*u)

2.另外若有多条sy该怎么创建如下relationship??可不可以不用for实现??

id sy_id u_id
1 1 1
2 1 2
3 2 1
4 2 2

*3.我看到说QuerySet执行delete()方法后,会同时删除中间表的记录,即删除双方的关联关系,
那是不是可以理解为不用再写remove 删除relationship?? *

新人第一次来v2提问,望大家帮我详细解答,thx!

1563 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/181361

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX