Suppose I have a model like this :
from django.db import models
from ckeditor.fields import RichTextField
from taggit.managers import TaggableManager
class Post(models.Model):
title = models.CharField(max_length=50)
pub_date = models.DateTimeField(auto_now_add=True)
content = RichTextField()
tags = TaggableManager()
def __unicode__(self):
return self.title
class Comments(models.Model):
post_id = models.ForeignKey(Post)
author = models.CharField(max_length=50)
content = models.TextField()
publish_date = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.content
Now for example i have many comments for a blog post id 1, then how would retrieve all the comments in that particular post ?
First of all you should rename your Comments
model to Comment
, as it represent a single comment. Then you would do this:
post = Post.objects.get(pk=1)
comments = post.comment_set.all()
You can read more about reverse relationships in the documentation .
Edit: Yes, you can also do this in a template. Provided you get a post object in a variable named post
you could do something similar to this (obviously you would need to add some HTML):
{% for comment in post.comment_set.all %}
{{ comment.author }}: {{ comment.content }}
{% endfor %}
When you have a relation like that, you can access related objects through the objects managers generated by Django.
For accessing all the comments from a post you can:
comments = one_post.comment_set.all()
you can change the manager´s name (comment_set) by specifying the related_name
option in the ForeignKey
field
post_id = Foreignkey(Post, related_name=comments)
and the you can:
comments = one_post.comments.all()
See: ForeignKey reference of Django documentation.
Answering to you last question:
You could write a template for listing the comments like this:
<ol>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ol>
Where comments
is a variable passed to template from the view. In others words, it's the value you obtain with comments = one_post.comment_set.all()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.