我不是很专业的django休息...
我用djangorest框架写了一个博客,例如,当我想获取与文章模型相关的所有记录或获取特定的文章时,没有问题
但我想做的是在单击用户名时向视图发送用户id(或用户名)。
并且作为结果显示与请求用户相关的Article模型的所有记录以及与其名字被点击的用户相关的Article模型的所有记录。
事实上,我想点击每个用户的名字,除了获得该用户的文章,与该请求相关的文章。用户也将采取
这是我目前所做的...
#models.py
class Article(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField
author = models.ForeignKey(User , on_delete = models.CASCADE)
content = models.TextField(null = True)
publish = models.DateTimeField(default = timezone.now)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
status = models.BooleanField(default = False)
def __str__(self):
return self.title
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
pic = models.ImageField(upload_to="img", blank=True, null=True)
def __str__(self):
return self.user.username
#views.py
class ArticleCreate(CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetail(RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class UserDetail(RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
class UserProfile(RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
#serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = "__all__"
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = "__all__"
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
exclude = ['updated' , 'created']
3条答案
按热度按时间gojuced71#
您应该直接使用
Q
对象在get_queryset()
方法中进行一些修改,以便:您还需要修改urls.py文件,以便在URL中包含
user_id
参数,从而:8fq7wneg2#
views.py
urls.py
omvjsjqw3#
示例URL:http://example.com/api/purchases?username=denvercoder9