【问题标题】:django foreign key savedjango外键保存
【发布时间】:2011-04-26 13:49:18
【问题描述】:

我有类似这样的模型。

class Mp3(models.Model):
    title=models.CharField(max_length=30)
    artist=models.ForeignKey('Artist')

Artist 模型如下所示:

class Artist(models.Model):
    name=models.CharField(max_length=100,default="Unknown")

我创建了 id 为 1 的艺术家。如何创建分配给该艺术家的 mp3?(例如,我需要它来进行这样的查询。

mp3=Mp3.objects.get(id=50)
mp3.artist

)我已经尝试过这样的事情

newMp3=Mp3(title="sth",artist=1)

但我得到了比

ValueError: Cannot assign "1": "Mp3.artist" must be a "Artist" instance.

我了解错误,但仍然不知道如何解决。谢谢你的帮助 最好的问候

【问题讨论】:

  • 您能否在此处发布答案以确保问答和后代的完整性?

标签: django models


【解决方案1】:

我认为从数据库中获取艺术家只是为了将其添加到 Mp3 模型中是不必要的,如果您已经拥有 艺术家 ID,则应该执行以下操作:

new_mp3 = Mp3(title='Cool song', artist_id=the_artist_id)
new_mp3.save()

请注意,artist 参数中的 _id,Django 将外键 id 存储在由 field_name 加上 _id 形成的字段中,因此您可以将外键 id 直接传递给该字段字段,而无需再次访问数据库来获取艺术家对象。

如果您的代码中不需要艺术家对象来处理其他内容,您应该使用这种方法。

【讨论】:

  • 有时可能需要确保具有指定 id 的实例存在。在这种情况下,获取实例将是可取的。在分配为外键之前确保实例存在且有效将是保护数据库免受错误数据影响的好习惯
【解决方案2】:
artist = Artist.objects.get(id=1)  
newMp3 = Mp3(title="sth", artist=artist)

【讨论】:

    【解决方案3】:

    答案是:

    newMp3=Mp3(title="sth", artist=the_artist)
    

    其中 'the_artist' 是 Artist 的实际实例

    【讨论】:

      【解决方案4】:

      答案是:

      artist_id = Artist.objects.objects.filter(id=1).first()
      new_mp3 = Mp3(title="sth", artist_id=artist_id)
      new_mp3.save()
      

      artist_id=artist_id(左边的值会从Mp3 fk获取Artist id)

      我来晚了……对不起!

      【讨论】:

        【解决方案5】:

        首先,创建或获取一个艺术家对象。

        艺术家 = Artist.objects.create(name="艺术家姓名")

        artist = Artist.objects.get(id=artist.id) 
        

        然后

        newMp3 = Mp3(title="sth", artist=artist)
        

        【讨论】:

          猜你喜欢
          • 2017-05-10
          • 2013-08-23
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 2017-11-16
          • 2022-01-17
          相关资源
          最近更新 更多