简体   繁体   English

批量删除多对多字段 django ORM

[英]Bulk delete with many-to-many field django ORM

Hii i have 1 model named College and in the model i have document_files field which is Many2ManyField now when i delete College objects i have to delete document_files also你好,我有 1 个 model 名为College ,在 model 中,我有document_files字段,现在当我删除 College 对象时,我必须删除 document_files

Below is my code and Model,下面是我的代码和 Model,

    college_datas = College.objects.filter(id__in=[1,2])
            if college_datas.exists():
                for college in college_datas:
                    college.document_files.all().delete()
                    college.delete()
class College(models.Model):
    name = models.CharField(null=True, blank=True)
    document_files = models.ManyToManyField(CollegeDocuments, through='CollegeDocumentsThrough')

      class Meta:
        verbose_name_plural = "College"

Here i am using for loop which i think its time consuming so i am finding efficent way to bulk delete the college queryset and also removes the associated Many2ManyField data also.我在这里使用 for 循环,我认为它很耗时,所以我找到了批量删除大学查询集的有效方法,并且还删除了关联的 Many2ManyField 数据。

First a clarifying question: Are you sure you want to use a ManyToManyField field here?首先是一个澄清的问题:你确定要在这里使用ManyToManyField字段吗? This allows several colleges to "own" the same document.这允许几所大学“拥有”同一份文件。 Is that intentional?那是故意的吗? In that case, you probably need some logic to make sure you only delete the documents that are not also related to other colleges.在这种情况下,您可能需要一些逻辑来确保您只删除与其他学院不相关的文档。

If, on the other hand, a document should only belong to a single college, I would remove the document_files on the College model and instead add a ForeignKey field called college on the CollegeDocuments model. If you then set on_delete=CASCADE on that field, the related documents will automatically be deleted along with the college.另一方面,如果文档只属于一所大学,我会删除College model 上的document_files ,而是在CollegeDocuments model 上添加一个名为collegeForeignKey字段。如果您随后在该字段上设置on_delete=CASCADE ,相关文件将随学院一起自动删除。 Have a look at the documentation for on_delete .查看on_delete的文档

If you want to stick to the ManyToManyField version and don't care about multiple colleges owning the same documents, you can (from the top of my head) do something along the lines of:如果您想坚持使用ManyToManyField版本并且不关心拥有相同文档的多个学院,您可以(从我的头顶开始)按照以下方式做一些事情:

CollegeDocuments.objects.filter(college_set__in=college_datas).delete()

If you don't intend to delete the documents, but only disassociate them from the colleges you are deleting, you may want to use clear() .如果您不打算删除文档,而只是将它们与要删除的大学取消关联,您可能需要使用clear() This still requires you to loop over the colleges, though.不过,这仍然需要您遍历大学。 To do it in bulk, you can (again, from the top of my head), do something like:要批量执行此操作,您可以(再次从我的头顶开始)执行以下操作:

CollegeDocumentsThrough.objects.filter(college__in=college_datas).delete()

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

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