django - 如何从 django 视图中为外键属性插入数据?
问题描述
这是我的具有两个外键属性的模型:
class Count(models.Model):
userId = models.ForeignKey(User, on_delete=models.CASCADE)
channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
rate = models.PositiveIntegerField(default=0)
def __str__(self):
return self.channelId.name
class Meta:
ordering = ["-id"]
我想在用户登录时插入一些数据,所以我在views.py文件中编写了以下代码
for i in range(1,10):
obj = Count.objects.filter(userId=request.user.id, channelId=cid)
if not obj:
o = Count.objects.create(id=Count.objects.all().count() + 1,userId=request.user.id, channelId=i,rate=0)
o.save()
i += 1
我的数据库中有从 1 到 10 的通道 ID,但出现以下错误:
ValueError: Cannot assign "1": "Count.channelId" must be a "News_Channel" instance.
请帮助插入数据。
解决方案
您正在尝试为 ForeignKey 插入一个整数,并且您需要该对象
for i in range(1,10):
obj = Count.objects.filter(userId=request.user.id, channelId=cid)
if not obj:
news_obj = News_Channel.objects.get(id=i)
o = Count.objects.create(id=Count.objects.all().count() + 1,userId=request.user.id, channelId=news_obj,rate=0)
o.save()
i += 1
推荐阅读
- delphi - Indy TLS1.2 报告为 SSL3
- python - 为什么 Unicode 字符串在 Python 2 和 3 中具有不同的内存占用?
- javascript - 尝试将http响应分配给数据源时出现角度表错误
- html - 如何将 2 层手风琴变成 3 层手风琴
- java - 依赖版本冲突 -> 不同的 slf4j 版本但不能排除错误的版本
- java - 获取 java.lang.NoClassDefFoundError: org/openqa/selenium/support/pagefactory/FieldDecorator
- python - 根据 Beautiful Soup 中的文本选择元素
- vba - 使用月份的可变范围 VBA
- spring - int-jdbc:inbound-channel-adapter 更新查询的系统变量
- sql - 如何将电话号码排除在错误的字段之外。SQL