I have probably a small problem. Namely how can i extract a last comment when i use 'post.comments.all'
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.content1)
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
Views
tag = request.GET.get('tag')
if tag == None:
my_tag = Posty.objects.all
print(my_tag)
else:
my_tag = Posty.objects.filter(created_tags__tag=tag)
print(my_tag)
If i tried use '[:1]' or last, this dont work.
CodePudding user response:
You can get the last comment with:
post.comments.latest('date_posted')
or if you want the latest per date_updated
, you use:
post.comments.latest('date_updated')
If you want to obtain the last comment per post, you can work with a Prefetch
object:
from django.db.models import OuterRef, Subquery
posts = Posty.objects.annotate(
latest_comment=Subquery(
CommentPost.objects.filter(
post=OuterRef('pk')
).values('content1').order_by('-date_posted')[:1]
)
)
then in the template, you can render with:
{% for post in posts %}
{{ post.last_comment }}
{% endfor %}