将值分配给外键字段

时间:2018-11-11 08:43:42

标签: django django-views

我很难为UserService模型分配标题,这是另一个模型的外键。

models.py

import io
from matplotlib.figure import Figure     
from matplotlib import pyplot as plt                 

fig = Figure(figsize=[4,4])                               
ax = fig.add_axes([.1,.1,.8,.8])                          
ax.scatter([1,2], [3,4])                                  

buf = io.BytesIO()
fig.savefig(buf, format='png')
plt.close(fig)
data=buf.getvalue()

# In my case I would have used Django for the webpage
response = HttpResponse(data, content_type='image/png')
return response

以下是视图中失败的代码部分:

class IndustryService(models.Model):    
    industryname = models.ForeignKey(Industry, on_delete=models.CASCADE)
    title = models.CharField(max_length=120)

class UserService(models.Model):  
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    title = models.ForeignKey(IndustryService, on_delete=models.CASCADE)

我得到的错误如下:

    industryservices = IndustryService.objects.filter(industryname=industry)

    for service in industryservices:                
        try:
            qs = UserService.objects.get(user=user, title=service.title)
        except: 
            userserv = UserService.objects.create(user=request.user)
            userserv.title = service
            userserv.save()

根据我的测试,我将值分配给“ title”外键字段的方式是错误的(即这两行代码)。

NOT NULL constraint failed: accounts_userservice.title_id

关于如何解决此问题的任何想法?谢谢!

1 个答案:

答案 0 :(得分:1)

您不必要地进行了两次更新。一次性创建商品:

res.status

或实例化而不保存,然后最后保存:

 userserv = UserService.objects.create(user=request.user, title=service)