【问题标题】:Foreign Key Access外键访问
【发布时间】:2017-03-13 01:16:06
【问题描述】:

--------------------------------------------MODELS.PY --------------------------------------------

class Artist(models.Model):
    name = models.CharField("artist", max_length=50) #will display "artist" in front of artist-name
    year_formed = models.PositiveIntegerField()

#   Initialization Example
#     newArtist = Artist(name = 'Artist Name', year_formed = 2015);
#     newArtist.save();




# Album will be a foreign key
# Many to 1 relation ie (Single artist -> many albums)
class Album(models.Model):
    name = models.CharField("album", max_length=50) #will display "album" in front of album-name
    artist = models.ForeignKey(Artist)

------------------SHELL------------------ ---------------

newArtist = Artist(name = 'GBA',year_formed = 1990)
newArtist.save()
album1 = Album(name = 'a',artist = newArtist)
album2 = Album(name = 'b',artist = newArtist)
album3 = Album(name = 'c',artist = newArtist)
album1.save()
album2.save()
album3.save()
allAlbums = Album.objects.all()

for e in allAlbums:
    print(e.artist.name) 

--------------------#导致错误----------- --

 Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 170, in __get__
    rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Album' object has no attribute '_artist_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 2, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 179, in __get__
    rel_obj = qs.get()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 385, in get
    self.model._meta.object_name
DB_start.models.DoesNotExist: Artist matching query does not exist.

我遵循文档中的正确语法,但会导致错误。如何成功访问外键字段?也尝试过 print (e__name)。

【问题讨论】:

  • 投反对票的人至少能解释一下原因吗..
  • 我不是投反对票的人,我也不知道你为什么被投反对票,但是你在 shell 中遇到的错误是什么?
  • 当你转储allAlbums 时你会得到什么。你能补充一下吗?
  • 有趣的是我复制了这个并得到了结果。没有错误。

标签: python django django-models


【解决方案1】:

您的问题来自您设置的密钥的位置。

class Artist():
    blah = models.TextField()


class Album()
    blah = models.ForeignKey(blah)

这就是数据库的工作方式

-干杯

https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py

52行

【讨论】:

猜你喜欢
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
相关资源
最近更新 更多