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