从模型中重置多对多字段

Reset many to many fields from model

我想用 django-orm 重置我所有 Post 的所有赞成票,不知道如何为此编写查询并将其应用于视图。此外,也许制作单独的投票模型比 Post.

中的一个字段更好。
class Post(models.Model):
    author = models.ForeignKey(
        User,
        related_name='posts',
        on_delete=models.SET_NULL,
        null=True
    )
    title = models.CharField(max_length=100)
    creation_date = models.DateTimeField(auto_now_add=True)
    link = models.URLField()
    upvotes = models.ManyToManyField(User, related_name='upvotes', blank=True)

I want to reset all upvotes from all my Posts

你可以这样做,例如:

Post.upvotes<b>.through</b>.objects.all()<b>.delete()</b>

例如,您可以在 data migration [Django-doc].

中执行此操作

这将清除多对多table中的记录。

Also, maybe it would be better to make separate upvote model than just a field in the Post.

一个ManyToManyField并不是一个真正的"field",它被存储为一个模型。您可以定义 through=… model [Django-doc],例如:

from django.conf import settings

class Post(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='posts',
        on_delete=models.SET_NULL,
        null=True
    )
    title = models.CharField(max_length=100)
    creation_date = models.DateTimeField(auto_now_add=True)
    link = models.URLField()
    upvotes = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='liked_posts',
        editable=False,
        <b>through='Upvote'</b>
    )

class Upvote(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    post = models.ForeignKey(
        'Post',
        on_delete=models.CASCADE
    )

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.

来自https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/ 在"Relation sets can be cleared:"

下快结束了

在您的示例中,它将是

p.upvotes.clear()

至于它在自己的模型中是否会更好,你是否需要在你的赞成票上有任何其他属性?比如它们是否无效或什么(idk?) 如果你认为你是,那么他们应该进入他们自己的模式

通过将中间模型设置为 through 属性,您仍然可以使用 Django 的 ManyToMany 字段及其附带的所有魔法 https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships