ValueError: Cannot use Queryset for “”: Use a Queryset for “”

余生颓废 提交于 2021-02-10 14:50:21

问题


I'm working on a little project using these models here and I'm trying to figure out a way to get a set of all the posts associated with users the currently authenticated user is following.

But I keep getting:

Cannot use QuerySet for "profile": Use a QuerySet for "User".

class Profile(models.Model):
    user = models.OneToOneField(User)
    isInstructor = models.BooleanField(default=False)
    isTutor = models.BooleanField(default=False)
    isStudent = models.BooleanField(default=False)
    isAdmin = models.BooleanField(default=False)
    following = models.ManyToManyField('self', related_name = "followers", blank=True, symmetrical=False)
    profile_image = ImageField(upload_to=get_image_path, blank=True, null=True)

class Post(models.Model):
    title = models.CharField(max_length=100)
    topic = models.CharField(max_length=50)
    description = models.CharField(max_length=1200)
    poster = models.ForeignKey(User, related_name="posts")
    likes = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now_add=True)
    tags = models.ManyToManyField(Tag, blank=True, related_name="posts")

    def __str__(self):
        return self.title

This is what keeps giving me the error.

current_user = Profile.objects.get(user = self.request.user)
Post.objects.filter(poster__in = current_user.following.all())

I searched around an found out that I had to use the __in operator whenever you want to filter by a list of things. But I keep getting the same error. Any help with explaining what the error means and what I can do to get around it would be much appreciated.


回答1:


Maybe try something like this,

Post.objects.filter(poster__id__in=current_user.following.all().values_list('id'))



回答2:


It's a simple problem: Profile class is different to User class, therefore, Profile'instance is different to User's instance.

Instead of use current_user you need to use current_user.user.

You can check the documentation.



来源:https://stackoverflow.com/questions/43827650/valueerror-cannot-use-queryset-for-use-a-queryset-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!