Как реализовать отношения "многие ко многим" между пользователями и комментариями?

у меня есть таблица user , post , comments в django

Здесь я хочу реализовать отношения "многие ко многим" между ними, если это возможно

Пожалуйста, помогите мне здесь

class Post(models.Model):
    title = models.CharField(max_length=50)
    desc = models.TextField(max_length=200)
    views = models.IntegerField(default=0)
    answers = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    view_status = models.BooleanField(default=False)
    like_status = models.BooleanField(default=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='users')
    post_image = models.ImageField(upload_to='upload/images')

    def __str__(self):
        return str(self.id)

def genarate_comment_id():
    last_comment_id = Comments.objects.all().order_by('cmnt_id').last().cmnt_id
    if last_comment_id:
        return last_comment_id + 1
    return 1001

class Comments(models.Model):
    cmnt_id = models.IntegerField(primary_key=True,default=genarate_comment_id)
    comment = models.TextField(max_length=500)
    pid = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')

    def __str__(self):
        return str(self.cmnt_id)

я хочу поддерживать каждое сообщение пользователя и его комментарии в виде постов

A ManyToManyField [Django-doc] between Comment and User does not seem sensical: it means the same comment is authored by many Users? Often this is a many-to-one relation: many comments can be written by the same user, and two comments can have the same user, so a ForeignKey [Django-doc]:

from django.conf import settings


class Post(models.Model):
    title = models.CharField(max_length=50)
    desc = models.TextField(max_length=200)
    views = models.IntegerField(default=0)
    answers = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    view_status = models.BooleanField(default=False)
    like_status = models.BooleanField(default=False)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='users'
    )
    post_image = models.ImageField(upload_to='upload/images')

    def __str__(self):
        return str(self.id)


class Comment(models.Model):
    cmnt_id = models.AutoField(primary_key=True)
    comment = models.TextField(max_length=500)
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments'
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='comments',
    )

    def __str__(self):
        return str(self.cmnt_id)

Note: Normally a Django model is given a singular name [django-antipatterns], so Comment instead of Comments.


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 [Django-doc].


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the User model to the Post model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the users relation to posts.


Note: Please don't generate primary keys: let the database assign unique primary keys, an AutoField [Django-doc] moves the logic from the server to the database: databases are more close to the data, and therefore picking a primary key can be done in an atomic way when inserting the record. This means no collisions can occur, and it is more efficient since we reduce the number of queries.

Вернуться на верх