使用 ORM 的 Django 查询:删除所有没有帖子的用户

Django Query Using ORM: Delete all Users with No Posts

我正在学习 Corey Django 教程。

给定用户模型和这个 Post 模型:

class Post(models.Model):
title       = models.CharField(max_length=100)
content     = models.TextField(max_length=10000)## was unrestircated
date_posted = models.DateTimeField(default=timezone.now)#auto_now_add=True - cant updated
author      = models.ForeignKey(User, on_delete=models.CASCADE)

我试图使用 ORM 删除所有没有任何用户的用户 Post,但是失败了。

试图查询所有用户和所有有帖子的用户,然后通过差分得到 Users_to_delete,但它引发了 'NotSupportedError': Calling QuerySet.delete() after difference () 不受支持。

如何删除所有没有帖子的用户? (使用 Django ORM) 任何帮助将不胜感激!

您可以过滤:

User.objects.filter(<b>post__isnull=True</b>).delete()

或稍短:

User.objects.filter(<b>post=None</b>).delete()

它将在 Post 模型上创建一个 LEFT OUTER JOIN,并且它只会保留与 Postid 为一行的那些NULL。因此,这些是没有 Post.

User

请注意,管理员用户可能 包括在内。您可能想使用:

User.objects.filter(<b>post=None, is_staff=False, is_superuser=False</b>).delete()

这将防止删除 User 超级用户或员工用户。


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.