首页 > 解决方案 > Get ID in Django

问题描述

I have a website made in Django, where people shall be able to post questions and answer them -just like a copy of Stack Overflow. When the user visits http://localhost/?post=Example it filters the database for posts with the name example. Later on I will do so there can only be exactly one post with the same name.
Currently it just renders the post/question in the HTML document using {{post.author}} for instance.

posts = Post.objects.filter(title=post)
context = {'posts':posts}#, "answers":answers}
return render(request, 'store/post.html', context)

On Stack Overflow it is possible to answer a question. There can be multiple ones. So in my code I did this by making a foreignkey in a model called Answer that is linking the answer to a post.
In the HTML document I made a for loop -just like I did for the post/question and looped through all answers and displayed them under the question.

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True)
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200, null=True)
    about = models.CharField(max_length=100, null=True, help_text="Use this field for notes about the customer.")
    image = models.ImageField(null=True, blank=True)

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = 'placeholder.png'
        return url

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=200, null=True)
    context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)])
    date = models.DateField(("Date"), default=date.today)
    author = models.ForeignKey(
        Customer,
        on_delete=models.CASCADE,
        null=True
    )

    def __str__(self):
        return self.title

class Answer(models.Model):
    title = models.CharField(max_length=200, null=True)
    context = models.TextField(max_length=1702, blank=True, validators=[MaxLengthValidator(1702)])
    date = models.DateField(("Date"), default=date.today)
    author = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title

So I think that I have to do this by ID, because when I look into the SQL browser (SQLCIPHER) it just displays an integer, but I am not sure.
This is the code that I have for the filtering of the posts and answers. I am just unsure how to obtain the variable postID and if this is the right way to do it.

posts = Post.objects.filter(title=post)
answers = Answer.objects.filter(post=postID)
context = {'posts':posts, "answers":answers}
return render(request, 'store/post.html', context)

This is the post.html site:

{% for post in posts %}
<div class="blogpost">
  <a class="post-title">{{ post.title }}</a>
  <a class="date-author">{{ post.date }} - {{ post.author }}</a>
  <div class="post-author-wrapper">
      <img class="thumbnail" src="{{ post.author.imageURL }}">
  </div>
  <div class="blogpost-content">{{ post.context | linebreaks }}</div>
</div>
{% endfor %}

{% for answer in answers %}
<div class="blogpost">
  <a class="post-title">{{ answer.title }}</a>
  <a class="date-author">{{ answer.date }} - {{ answer.author }}</a>
  <div class="post-author-wrapper">
      <img class="thumbnail" src="{{post.author.imageURL}}">
  </div>
  <div class="blogpost-content">
    Here is a quick tutorial on how to do it: https://example.com
  </div>
</div>
{% endfor %}

标签: pythondjango

解决方案


如果只有一篇文章,过滤没有意义,你应该使用get_object_or_404(…)[Django-doc]

from django.shortcuts import get_object_or_404

# …

post = get_object_or_404(Post, title=post)

thenpost单个 Post对象,而不是对象的集合Post。然后,您可以使用answer_set获取相关答案:

answers = post.answer_set.all()

由于post是单个帖子,因此您省略了{% for post in posts %}which 是无意义的。


推荐阅读