Reputation: 5730
I made a posts
application and have a comment
model like this
from django.db import models
from django.conf import settings
from posts.models import Post
class Comment(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
post = models.ForeignKey(Post)
content = models.CharField(max_length=400)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return self.content
And I login, and post some comments:
After I delete user rightx2
, it becomes null
or None
:
Worse, It changed the order
of comments, too!
I want to make username
still there, and keep ordering, too.
Any ideas?
Upvotes: 1
Views: 435
Reputation: 722
it was setting null
because you defined the author
as null=True
and on_delete=models.SET_NULL
, to keep the author id intact you can use on_delete=models.DO_NOTHING
but as the doc says
you need to manually add the
ON DELETE
constraint into the database field
but to really keep the username here you need to denormalize it and use a separate username
field which you need to set on saving the comment.
Upvotes: 1
Reputation: 315
Instead of using models.ForeignKey
to set author
attribute in Comment
model, try CharField
, and add an assignment line in your comment function in views.py
to let this Comment.author
attribute equals to its author name every time an author
create it.
Hope this helps :)
Upvotes: 1