我刚刚开始使用Django Rest Framework,所以我还不完全确定到底发生了什么。但我有一个用户模型,一个朋友模型和一个帖子模型,我还有我的序列化器和视图。但是,我无法弄清楚如何从用户的朋友那里归还所有帖子。任何帮助将不胜感激。
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True, db_index=True)
password1 = models.CharField(max_length=50)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
image = models.FileField(upload_to='photos', null=True, blank=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
class Meta:
unique_together = (('username', 'password1'),)
class Friendship(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
creator = models.ForeignKey(CustomUser, related_name="friendship_creator")
friend = models.ForeignKey(CustomUser, related_name="friends")
class Post(models.Model):
poster = models.ForeignKey(CustomUser)
body = models.CharField(max=200)
def save(self, *args, **kwargs):
super(Post, self).save(*args, **kwargs)
serializers.py
class FriendSerializer(HyperlinkedModelSerializer):
class Meta:
model = Friendship
fields = ('creator', 'friend', 'created_at')
readonly_fields = 'created_at'
class CustomUserSerializer(HyperlinkedModelSerializer):
friends = FriendSerializer(many=True)
class Meta:
model = CustomUser
fields = ('email', 'username', 'password1', 'image', 'friends')
readonly_fields = 'image'
views.py
class FriendViewSet(ModelViewSet):
queryset = CustomUser.objects.all()
serializer_class = FriendSerializer
class UserProfileViewSet(RetrieveModelMixin, UpdateModelMixin, GenericViewSet):
queryset = CustomUser.objects.all()
serializer_class = CustomUserSerializer
答案 0 :(得分:1)
这可能会让你开始,
所以你需要先做的就是得到所有朋友,你可以通过
来做到这一点friends = <user_objects>.Friendship_set.all()
详细了解here。
既然您拥有该特定用户的所有朋友,请将他们的ID转换为列表并使用列表过滤器。
Post.objects.filter(poster__id__in=[list_of_ids_of_friends])
有关外键属性的过滤,请参阅this answer。