简体   繁体   English

在 django 中,如何获取具有精确外键的所有数据? 例如,获取外键 = 1 或 2 的所有帖子或

[英]In django, how to get all data with exact foreign key? example, get all posts with foreign key = 1 or 2 or

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse


class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

Hello im new to django and this is my model and I have 2 tables "auth_user" table and "blog_post" table.您好,我是 django 的新手,这是我的 model,我有 2 个表“auth_user”表和“blog_post”表。 Inside blog_post table I have a column called "author_id" which is the foreign key between "blog_post" table and "auth_user" table.在 blog_post 表中,我有一个名为“author_id”的列,它是“blog_post”表和“auth_user”表之间的外键。 The question is how can i get all posts from "blog_post" table when foreign key = 1 or 2 or 3 or.. etc. Thanks before hand.问题是当外键 = 1 或 2 或 3 或.. 等时,我如何从“blog_post”表中获取所有帖子。在此先感谢。

If you meant that you wanted to filter by the author, then what you can do is provide the author_id as a query parameter on your request, and have the view serving the request filter by the author.如果您的意思是要按作者过滤,那么您可以做的是在您的请求中提供author_id作为查询参数,并让视图服务于作者过滤的请求。

Post.objects.filter(author_id=author_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM