Dori's Python Life in Words Journal

Creation of the Comment model


Creating comments from other users is quite common for a blog application. We set relations to the Post model and to our User model. The User model is for authentication later in our process of creating this blog application.

create Comment model, explain why used user and post and why on_delete=models.SET_NULL and on_delete=models.CASCADE

# blog/models.py

class Comment(models.Model):
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)
    user = models.ForeignKey(
        "account.User",
        on_delete=models.SET_NULL,
        null=True,
        related_name="comment_users",
    )
    post = models.ForeignKey(
        "blog.Post", on_delete=models.CASCADE, related_name="comments"
    )

    class Meta:
        ordering = ["created"]
        indexes = [models.Index(fields=["created"])]

    @property
    def get_full_name(self):
        return f"{self.user.first_name} {self.user.last_name}"

    def __str__(self):
        return f"Comment by {self.get_full_name} on {self.post}"

Legend:

    • on_delete=models.SET_NULL: To maintain data integrity, the on_delete option determines how the database handles the deletion of referenced data. The on_delete behaviour controls what happens when the model (in our case the Comment instance) is deleted.
    • on_delete=models.SET_NULL: The option SET_NULL sets the ForeignKey to null, but we need to specify null=True in our model. When a User instance is deleted, the user field in the Comment instance is set to NULL (i.e. None) instead of deleting the comment itself.
    • on_delete=models.CASCADE: This option will delete the Comment instance(s) when the Post instance is deleted.

We need to add the Comment model to the admin.py file to display the Comment instances in the admin panel.

# blog/admin.py

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ["user", "post", "created", "active"]
    list_filter = ["active", "created", "updated"]
    search_fields = ["user__username", "user__email", "body"]

Designed by BootstrapMade and modified by DoriDoro