python - Django - 在外键模型的模型上设置默认图像

标签 python django django-models

我遇到的问题如下。我有两个模型,如下所示,“配置文件”和“图像”,其中每个图像实例通过外键连接到单个配置文件,因此多个图像将链接到单个配置文件。由此,我想通过返回相关图像集中的第一个图像来为配置文件设置默认图像。

class Profile(models.Model):
    ...
    def default_img(self):
        if self.p_image.count() > 0:
            return self.p_image[0]
        else:
            return False
class Image(models.Model):
    ...
    related_profile = models.ForeignKey(Profile, related_name='p_image')
    img_path = models.ImageField(upload_to=profile_img,null=True,verbose_name='Image URL',height_field='h_field',width_field='w_field')

使用我尝试执行的方法,Django 通过“return self.p_image[0]”行返回错误“'RelatedManager'对象不支持索引',我尝试从集合中获取第一个对象。

有关如何获取第一个对象(无需搜索整个 Image 对象集)的任何帮助吗?

谢谢

最佳答案

索引可以在Queryset中使用,不能在RelatedManager中使用。使用

return self.p_image.all()[0]

This will raise a IndexError if no objects match the given criteria. Refer

关于python - Django - 在外键模型的模型上设置默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193028/

相关文章:

django - 在 Windows 中为 django 安装 postgresql

python - Django,在某个id之前查询对象

android - Kivy 应用程序在设备上运行时不使用 VKeyboard

python - 如何创建具有并行的多行字形/文本的 GUI,其中字形具有 x 和 y 坐标

python - next 方法对于 python 迭代器来说是引用透明的吗?

android - 验证、识别和存储有关用户的敏感信息的最佳方式是什么?

django - 为什么 Django 在使用 @login_required 装饰器时有太多登录重定向?

javascript - 尝试使用 Angular 将部分内容加载到我的 django 模板一侧

django - 在保存 Django 期间将参数从部分表单传递到模型

python - 子模型中的 Django 用户模型