如何从Django视图中为外键属性插入数据?

时间:2019-05-25 20:00:41

标签: django python-3.x django-models django-views django-orm

这是我的模型,具有两个外键属性:


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

我的数据库中的通道ID从1到10,但是出现以下错误:

ValueError: Cannot assign "1": "Count.channelId" must be a "News_Channel" instance.

请帮助插入数据。

1 个答案:

答案 0 :(得分:1)

您正在尝试为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