2017-04-07 72 views
0

我正在创建一个UserProfile模型,用户可以在其中为其个人资料添加尽可能多或最少的图像。我已经使用图像模式,像这样考虑:Django - 将多个图像/数据添加到UserProfile模型的一个字段

class Image(models.Model): 
    related_profile = models.ForeignKey(UserProfile) # UserProfile is the name of the model class 
    user_picture = models.ImageField(upload_to=get_user_img, blank=True, null=True, height_field='height_field', width_field='width_field') 

当有人访问其UserProfile然后所有的Image对象将显示;但是,当我想编辑UserProfile(即删除一个或两个图像),但无法做到这一点。 的“实例”不希望返回多个Image对象进行编辑,因为我得到错误:

get() returned more than one Image -- it returned 2!

有这样这表明过滤器(过类似的问题),而不是得到()这里django - get() returned more than one topic 尽管这使用了ManyToMany关系,并且该解决方案对我的错误无效。

有没有人知道任何好的方法来重组这个,以便我可以从同一页面编辑每个模型对象(所以不会返回上述错误)?

就像标题所暗示的那样,我想知道是否有可能将一组图像作为列表存储在UserProfile模型的一个字段中,因为这是一个潜在的想法。

回答

0

你在正确的轨道上。 Model.objects.get()方法预计查询结果是一行(实例),然后返回。但在你的情况下,UserProfile可以有任何数量的相关图像。所以你需要遍历你将要从查询中得到的(可能的)多个结果,然后对每个结果进行一些处理。更多类似:

# there is only ONE UserProfile per userid.. that is to say, userid is a 
# unique key.. so I can use get() to fetch it 

profile = UserProfile.objects.get(userid=the_userid) 

# now I need to get each image 
for image in Image.objects.filter(user_profile=profile): 
    # do something with image.... 

如果你只需要镜像实例和不需要用户配置的实例,那么你就可以缩短这个联接:

for image in Image.objects.filter(user_profile__userid=the_userid): 
    # do something with image.... 

我要补充,这有什么好用图像做,但适用于任何时候使用Django从数据库中获取数据。任何具有多行的查询都需要以这种方式完成。

相关问题