Foreign Key Access

2024/10/15 2:30:02

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

class Artist(models.Model):name = models.CharField("artist", max_length=50) #will display "artist" in front of artist-nameyear_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-nameartist = 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) 

--------------------#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 getself.model._meta.object_name
DB_start.models.DoesNotExist: Artist matching query does not exist.

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.

Answer

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

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

This is how the database will work

-Cheers

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

52 line

https://en.xdnf.cn/q/117883.html

Related Q&A

ValueError: could not broadcast input array from shape (22500,3) into shape (1)

I relied on the code mentioned, here, but with minor edits. The version that I have is as follows:import numpy as np import _pickle as cPickle from PIL import Image import sys,ospixels = [] labels = []…

VGG 16/19 Slow Runtimes

When I try to get an output from the pre-trained VGG 16/19 models using Caffe with Python (both 2.7 and 3.5) its taking over 15 seconds on the net.forward() step (on my laptops CPU).I was wondering if …

Numpy vs built-in copy list

what is the difference below codesbuilt-in list code>>> a = [1,2,3,4] >>> b = a[1:3] >>> b[1] = 0 >>> a [1, 2, 3, 4] >>> b [2, 0]numpy array>>> c …

Scrapy returns only first result

Im trying to scrape data from gelbeseiten.de (yellow pages in germany)# -*- coding: utf-8 -*- import scrapyfrom scrapy.spiders import CrawlSpiderfrom scrapy.http import Requestfrom scrapy.selector impo…

Softlayer getAllBillingItems stopped working?

The following python script worked like a charm last month:Script:import SoftLayer client = SoftLayer.Client(username=someUser, api_key=someKey) LastInvoice = client[Account].getAllBillingItems() print…

Looking for a specific value in JSON file

I have a json file created by a function. The file is looks like this :{"images": [{"image": "/WATSON/VISUAL-REC/../IMAGES/OBAMA.jpg", "classifiers": [{"cla…

How to put many numpy files in one big numpy file without having memory error?

I follow this question Append multiple numpy files to one big numpy file in python in order to put many numpy files in one big file, the result is: import matplotlib.pyplot as plt import numpy as np i…

scraping : nested url data scraping

I have a website name https://www.grohe.com/in In that page i want to get one type of bathroom faucets https://www.grohe.com/in/25796/bathroom/bathroom-faucets/grandera/ In that page there are multiple…

How to trigger an action once on overscroll in Kivy?

I have a ScrollView thats supposed to have an update feature when you overscroll to the top (like in many apps). Ive found a way to trigger it when the overscroll exceeds a certain threshold, but it tr…

Python - Print Each Sentence On New Line

Per the subject, Im trying to print each sentence in a string on a new line. With the current code and output shown below, whats the syntax to return "Correct Output" shown below?Codesentenc…