如何从 Django 视图中为外键属性插入数据?
How to insert data in for foreign key attribute from django views?
这是我的模型,有两个外键属性:
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
这是我的模型,有两个外键属性:
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