首页 > 解决方案 > 如何从 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.

请帮助插入数据。

标签: djangopython-3.xdjango-modelsdjango-viewsdjango-orm

解决方案


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

推荐阅读