'QuerySet' 对象没有属性 'x'

'QuerySet' object has no attribute 'x'

我想转到用户页面并查看他们的照片,所以我试图将对象分配给外键,但我一直在 AttributeError 上收到 [=24] 上的错误=]/ 'QuerySet' 对象没有属性 'file'。我觉得问题出在我的语法上,但我真的不知道为什么它不能读取我的上传文件模型对象,但它能够读取我的配置文件对象。

views.py

def profile_view(request, *args, **kwargs,):
    #users_id = kwargs.get("users_id")
    #img = Uploads.objects.filter(profile = users_id).order_by("-id")
    context = {}
    user_id = kwargs.get("user_id")
    try:
        profile = Profile.objects.get(user=user_id)
        img = profile.uploads_set.all()
    except:
        return HttpResponse("Something went wrong.")
    if profile and img:
        context['id'] = profile.id
        context['user'] = profile.user
        context['email'] = profile.email
        context['profile_picture'] = profile.profile_picture.url
        context['file'] = img.file.url


        return render(request, "main/profile_visit.html", context)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)
    banner_picture = models.ImageField(default = 'bg_image.png', upload_to = "img/%y", null = True, blank = True)

    def __str__(self):
        return f'{self.user.username} Profile'



class Uploads(models.Model):
    album = models.ForeignKey('Album', on_delete=models.SET_NULL,null=True,blank=True)
    caption = models.CharField(max_length = 100, blank=True, null = True)
    file = models.FileField(upload_to = "img/%y", null = True)
    profile = models.ForeignKey(Profile, on_delete = models.CASCADE, default = None, null = True)
    id = models.AutoField(primary_key = True, null = False)


    def __str__(self):
        return str(self.file) and f"/single_page/{self.id}"

class Album(models.Model):
    name=models.CharField(max_length=400)

这个:

img = profile.uploads_set.all()

是一个查询集,因此它没有属性 file

您可以对其进行迭代,其各个成员将具有 file 属性。

url_list = []
for i in img:
    url_list.append(i.file.url)

然后将为您提供所需网址的列表。

您也可以将其作为列表理解来完成:

url_list = [i.file.url for i in img]

img = profile.uploads_set.all() 从这里 img 是一个查询集。 file 是上传实例的一个字段。

您可以执行以下操作。

context['file'] = [im.file.url for im in img]

通过这种方式您可以获得一个配置文件的所有文件。