有人可以解释一下,如果用户是订阅者,我如何过滤用户帖子?
'QuerySet'对象没有属性'subs'
我使用自定义用户
class Every(AbstractBaseUser):
user = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True)
name = models.CharField(max_length=30, blank=True)
这是帖子模型:
class Post(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
text = models.TextField(max_length=1200)
订阅者模型:
class Sub(models.Model):
user = models.OneToOneField(User, related_name='user')
subs = models.ManyToManyField(User, blank=True, related_name='subs')
我正在尝试使用的视图:
def tape(request, every_id):
context = {}
context.update(csrf(request))
post_form = PostForm
pform = post_form
sub = Sub.objects.filter(subs=every_id)# here I get users that intersting for my user
tape = Post.objects.filter(user=sub.subs).order_by("-timestamp")
username = request.user
context = {"username": username, "pform": pform, "tape": tape, "sub": sub,}
return render(request, 'tape.html', context)
答案 0 :(得分:1)
实际上使用类视图会更好。但这是一个平常的答案。我们需要在开始过滤帖子之前获得订阅和订阅者ID
这里甚至更多: - )
def get_user_id_list(user):
"""Returns a list of subscribers's ids"""
try:
sub = user.user
Sub.DoesNotExist:
return []
return sub.subs.all().values_list('user_id', flat=True)
def get_user_id_list_2(user):
"""Returns a list of subscription's ids"""
return user.subs.values_list('user_id', flat=True)
def tape(request):
pform = PostForm
user_id_list = get_user_id_list_2(request.user)
logger.info('user_id_list = {}'.format(user_id_list))
tape = Post.objects.filter(user_id__in=user_id_list).order_by("-timestamp")
username = request.user
context = {
"username": username,
"pform": pform,
"tape": tape,
"sub": sub,
}
return render(request, 'tape.html', context)