Django: get info from same table based on column vsalue for data record
I am building a forum application for a website and have a "quote_id" column in the Posts table to put in a post_id if someone quotes a certain post to reply to. That is part of the Posts table just like all other posts. However, when I retrieve all records that match the topic that corresponds to the topic chosen, there will be a few that quote other posts. I cannot seem to find a way to do this in Django ORM to retrieve the quoted posts info to display along with the post that quoted it(to display within the post that quoted it). What I have so far is below:
def show_topic_posts(request,forum_id,topic_id):
posts = Post.objects.filter(topic_id=topic_id)
topic = Topic.objects.get(topic_id=topic_id)
context = RequestContext(request,{'posts':posts,'topic':topic})
return render_to_response('forums/topics_posts.html',context_instance=context)
c开发者_Python百科lass Post(models.Model):
post_id = models.AutoField(primary_key=True)
forum_id = models.ForeignKey(Forum)
topic_id = models.ForeignKey(Topic)
post_date_time = models.DateTimeField(auto_now=True)
post_user_id = models.ForeignKey(User)
post_quote_id = models.IntegerField(null=True,blank=True)
post_body = models.TextField()
post_likes = models.IntegerField(default=0)
post_is_flagged = models.BooleanField(default=False)
def __unicode__(self):
return '%i' % self.topic_id
def get_absolute_url(self):
return '/forums/%s/%s/%s/' % (str(self.forum_id.pk), str(self.topic_id.pk),self.topic_id)
How in the world can I do this? Ive searched Google and Django Book and Django website trying to find a way to do this. Thanks!
Drop the post_quote_id
field and create a recursive m2m-relationship for your Post
model.
quoted_by = models.ManyToManyField('self')
That way posts can refer to other posts and you should be able to easily fetch the related posts for all your posts matching a certain topic.
example_post = Post.objects.get(pk=1)
posts_that_quote_my_example_post = example_post.quoted_by.all()
And in your template you could fetch the posts that quote a specific post like this:
<ul>
{% for quote in post.quoted_by.all %}
<li>{{ quote.post_body }}</li>
{% endfor %}
</ul>
If you want to additionally store the person that quoted a certain post you'll need to add an intermediary model using the through parameter.
精彩评论