我jush有一个模型有两个字段,一个是post,anther是一个外键,它与django User模型有关。就像这样:
from django.contrib.auth.models import User
class Post(models.Model):
post = models.CharField(max_length=20)
author = models.ForeignKey(User, related_name='posts')
现在我定义一个用户序列化器禁止Post,就像这样:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'post', 'author')
class UserSerialzier(serializers.ModelSerializer):
posts = PostSerializer()
class Meta:
model = get_user_model()
fields = ('id', 'username', 'snippets', 'posts')
我只想返回一个包含用户数据和帖子数据的json。但是,我想得到的帖子数据是按条件过滤的,而不是所有的帖子数据,我的观点是这样的:
class UserDetail(generics.RetrieveAPIView):
serializer_class = HomeSerializer
def get_queryset(self):
post_set = self.request.user.posts.filter(post='python')
query_set = User.objects.filter(posts=post_set, username='admin')
return query_set
我希望得到结果:
{
"id": 1,
"username": "rsj217",
"posts": [
{
"id": 1,
"post": "python",
"author": {
"id": 1,
"username": "rsj217",
}
},
{
"id": 2,
"post": "python",
"author": {
"id": 1,
"username": "rsj217",
}
}
]
}
但事实上,我得到的结果如下:
{
"id": 1,
"username": "rsj217",
"posts": [
{
"id": 1,
"post": "python",
"author": {
"id": 1,
"username": "rsj217",
}
},
{
"id": 2,
"post": "python",
"author": {
"id": 1,
"username": "rsj217",
}
},
{
"id": 3,
"post": "ruby",
"author": {
"id": 1,
"username": "rsj217",
}
}
]
}
我无法过滤帖子字段" ruby" ??? ,我不知道哪里消失了
答案 0 :(得分:0)
我认为检索查询集的方式是错误的。试试这样:
query_set = User.objects.filter(post__in=post_set, username='admin')