我想在Django多个表中执行一个简单的插入,例如:
INSERT INTO "chat_room_users" ("room_id", "user_id") values (35, 6)
这是我的 models.py :
class User(AbstractBaseUser):
...
class Room(models.Model):
users = models.ManyToManyField(User, related_name='rooms')
...
和 code.py :
print('start')
room = Room.objects.get(id=35)
user = User.objects.get(id=6)
room.users.add(user)
print('finish')
在这种情况下,Django执行3个数据库查询,这里是日志:
start
SELECT "chat_room"."id", "chat_room"."name", "chat_room"."disabled" FROM "chat_room" WHERE "chat_room"."id" = 35; args=(35,)
SELECT "chat_user"."id", "chat_user"."password", "chat_user"."last_login", "chat_user"."username", "chat_user"."sex" FROM "chat_user" WHERE "chat_user"."id" = 6; args=(6,)
BEGIN; args=None
SELECT "chat_room_users"."user_id" FROM "chat_room_users" WHERE ("chat_room_users"."room_id" = 35 AND "chat_room_users"."user_id" IN (6)); args=(35, 6)
INSERT INTO "chat_room_users" ("room_id", "user_id") SELECT 35, 6; args=(35, 6)
finish
我希望Django只执行1个插入查询,而不是那些没有用处的选择。如何使用Django QuerySet实现这一目标?
提前感谢您的帮助!
致以最诚挚的问候,
答案 0 :(得分:6)
您可以通过Room.users.through
访问自动处理的直通模型。所以:
Room.users.through.objects.create(room_id=35, user_id=6)