Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - 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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If there is exactly one post, it does not make sense to filter, you should use get_object_or_404(…) [Django-doc]:

from django.shortcuts import get_object_or_404

# …

post = get_object_or_404(Post, title=post)

then post is a single Post object, not a collection of Post objects. You can then make use of the answer_set to obtain the related answers:

answers = post.answer_set.all()

Since post is a single post, you thus omit the {% for post in posts %} which is non-sensical.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...