Django - 从ForeignKey模型在模型上设置默认图像

时间:2018-01-10 17:32:45

标签: python django django-models

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

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会返回错误' 'RelatedManager' object does not support indexing'这是通过' return self.p_image[0]',我尝试从集合中获取第一个对象。

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

由于

1 个答案:

答案 0 :(得分:1)

索引可以在private static void ConfigureSwagger(HttpConfiguration config) { // add the versioned IApiExplorer and capture the strongly-typed implementation (e.g. VersionedApiExplorer vs IApiExplorer) // note: the specified format code will format the version as "'v'major[.minor][-status]" var apiExplorer = config.AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV"); config .EnableSwagger(swagger => { // build a swagger document and endpoint for each discovered API version swagger.MultipleApiVersions( (apiDescription, version) => apiDescription.GetGroupName() == version, info => { foreach (var group in apiExplorer.ApiDescriptions) { var description = "AAAA API."; if (group.IsDeprecated) { description += " This API version has been deprecated."; } info.Version(group.Name, $"AAAA API {group.ApiVersion}") .Contact(c => c.Name("AAAA").Email("AAAA@AAAA.com")) .Description(description) .License(l => l.Name("AAAA").Url("www.AAAA.com")) .TermsOfService("AAAA. All rights reserved."); } }); // add a custom operation filter which sets default values swagger.OperationFilter<SwaggerDefaultValues>(); // integrate xml comments swagger.IncludeXmlComments(XmlCommentsFilePath); //swagger.RootUrl(req => SwaggerDocsConfig.DefaultRootUrlResolver(req) + "/api"); }) .EnableSwaggerUi(swagger => swagger.EnableDiscoveryUrlSelector()); } 中使用,而不能在Queryset中使用。使用

RelatedManager
  

如果没有对象符合给定条件,则会引发IndexError。 Refer