外键访问

编程入门 行业动态 更新时间:2024-10-26 17:18:39
本文介绍了外键访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

--------------------------------------------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 --------------------------------

-----------------------------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)

-------------- ------#结果错误-------------------------

--------------------#Results in error-------------------------

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.

我遵循正确的语法作为文档,但导致错误。如何成功访问外键字段?尝试打印(e__name)。

I am following the correct syntax as documentation yet results in error. How can I successfully access the foreign key fields? Have tried print (e__name) as well.

推荐答案

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

Your problem comes from the placement of the key you have set up.

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

这是数据库将工作

-Cheers

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

52行

更多推荐

外键访问

本文发布于:2023-10-29 02:57:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538531.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!