简体   繁体   English

缩短Python Django DB查询

[英]Shorten a Python Django DB query

We have m2m relationship between E and U models: 我们有EU模型之间的m2m关系:

class E(models.Model):
    us = models.ManyToManyField('U', related_name='events', symmetrical=False)

class U(models.Model):
    pass

Now we want to remove all links for U with pk=2. 现在我们要删除pk = 2的U的所有链接。

I wrote this code: U.events.through.objects.filter(u=2).delete() . 我写了这段代码: U.events.through.objects.filter(u=2).delete()

Can this code be shortened/simplified? 可以缩短/简化此代码吗?

You could do something like: 您可以执行以下操作:

U.objects.get(pk=2).events.clear()

There are some useful examples in the Django documentation: Django文档中有一些有用的示例:

https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/ https://docs.djangoproject.com/zh-CN/2.0/topics/db/examples/many_to_many/

As a side note, you don't need symmetrical=False on your many to many definition. 附带说明一下,您无需在多对多定义中使用symmetrical=False Quoting from the Django documentation: 引用Django文档:

Only used in the definition of ManyToManyFields on self. 仅用于self的ManyToManyFields的定义。

See: 看到:

https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField.symmetrical https://docs.djangoproject.com/zh-CN/2.0/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

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

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