{"id":75311,"date":"2020-01-18T14:17:57","date_gmt":"2020-01-18T08:47:57","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75311"},"modified":"2024-04-12T14:17:13","modified_gmt":"2024-04-12T08:47:13","slug":"basic-data-access","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/","title":{"rendered":"Basic Data Access"},"content":{"rendered":"<p>Once you\u2019ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell <span lang=\"EN-US\">from within your virtual environment and typing the following:<\/span><\/p>\n<pre class=\"VSKILLbodytext\"><span lang=\"EN-US\">&nbsp;&gt;&gt;&gt; from books.models import Publisher\n&gt;&gt;&gt; p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',\n... city='Berkeley', state_province='CA', country='U.S.A.',\n... website='http:\/\/www.apress.com\/')\n&gt;&gt;&gt; p1.save()\n&gt;&gt;&gt; p2 = Publisher(name=\"O'Reilly\", address='10 Fawcett St.',\n... city='Cambridge', state_province='MA', country='U.S.A.',\n... website='http:\/\/www.oreilly.com\/')\n&gt;&gt;&gt; p2.save()\n&gt;&gt;&gt; publisher_list = Publisher.objects.all()\n&gt;&gt;&gt; publisher_list\n&lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt;<\/span><\/pre>\n<p>These few lines of code accomplish quite a bit. Here are the highlights:<\/p>\n<ul>\n<li>First, we import our Publisher model class. This lets us interact with the database table that contains publishers.<\/li>\n<li>We create a Publisher object by instantiating it with values for each field \u2013 name, address, etc.<\/li>\n<li>To save the object to the database, call its save() method. Behind the scenes, Django executes an SQL INSERT statement here.<\/li>\n<li>To retrieve publishers from the database, use the attribute Publisher.objects, which you can think of as a set of all publishers. Fetch a list of all Publisher objects in the database with the statement Publisher.objects.all(). Behind the scenes, Django executes an SQL SELECT statement here.<\/li>\n<\/ul>\n<p>One thing is worth mentioning, in case it wasn\u2019t clear from this example. When you\u2019re creating objects using the Django model API, Django doesn\u2019t save the objects to the database until you call the save() method:<\/p>\n<pre>p1 = Publisher(...)\n# At this point, p1 is not saved to the database yet!\np1.save()\n# Now it is.<\/pre>\n<p>If you want to create an object and save it to the database in a single step, use the objects.create() method. This example is equivalent to the example above:<\/p>\n<pre>&gt;&gt;&gt; p1 = Publisher.objects.create(name='Apress',\n... address='2855 Telegraph Avenue',\n... city='Berkeley', state_province='CA', country='U.S.A.',\n... website='http:\/\/www.apress.com\/')\n&gt;&gt;&gt; p2 = Publisher.objects.create(name=\"O'Reilly\",\n... address='10 Fawcett St.', city='Cambridge',\n... state_province='MA', country='U.S.A.',\n... website='http:\/\/www.oreilly.com\/')\n&gt;&gt;&gt; publisher_list = Publisher.objects.all()\n&gt;&gt;&gt; publisher_list \n&lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt;<\/pre>\n<p>Naturally, you can do quite a lot with the Django database API \u2013 but first, let\u2019s take care of a small annoyance.<\/p>\n<h3>Adding Model String Representations<\/h3>\n<p>When we printed out the list of publishers, all we got was this unhelpful display that makes it difficult to tell the Publisher objects apart:<\/p>\n<pre>&lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt;<\/pre>\n<p>We can fix this easily by adding a method called __str__() to our Publisher class. A __str__() method tells Python how to display a human-readable representation of an object. You can see this in action by adding a __str__() method to the three models:<\/p>\n<pre>from django.db import models\n\nclass Publisher(models.Model):\nname = models.CharField(max_length=30)\naddress = models.CharField(max_length=50)\ncity = models.CharField(max_length=60)\nstate_province = models.CharField(max_length=30)\ncountry = models.CharField(max_length=50)\nwebsite = models.URLField()\n\ndef __str__(self):\nreturn self.name\n\nclass Author(models.Model):\nfirst_name = models.CharField(max_length=30)\nlast_name = models.CharField(max_length=40)\nemail = models.EmailField()\n\ndef __str__(self):\nreturn u'%s %s' % (self.first_name, self.last_name)\n\nclass Book(models.Model):\ntitle = models.CharField(max_length=100)\nauthors = models.ManyToManyField(Author)\npublisher = models.ForeignKey(Publisher)\npublication_date = models.DateField()\n\ndef __str__(self):\nreturn self.title<\/pre>\n<p>As you can see, a __str__() method can do whatever it needs to do in order to return a representation of an object. Here, the __str__() methods for Publisher and Book simply return the object\u2019s name and title, respectively, but the __str__() for Author is slightly more complex \u2013 it pieces together the first_name and last_name fields, separated by a space. The only requirement for __str__() is that it return a string object. If __str__() doesn\u2019t return a string object \u2013 if it returns, say, an integer \u2013 then Python will raise a TypeError with a message like:<\/p>\n<pre>TypeError: __str__ returned non-string (type int).<\/pre>\n<p>For the __str__() changes to take effect, exit out of the Python shell and enter it again with python manage.py shell. (This is the simplest way to make code changes take effect.) Now the list of Publisher objects is much easier to understand:<\/p>\n<pre>&gt;&gt;&gt; from books.models import Publisher\n&gt;&gt;&gt; publisher_list = Publisher.objects.all()\n&gt;&gt;&gt; publisher_list\n&lt;QuerySet [&lt;Publisher: Apress&gt;, &lt;Publisher: O'Reilly&gt;]&gt;<\/pre>\n<p>Make sure any model you define has a __str__() method \u2013 not only for your own convenience when using the interactive interpreter, but also because Django uses the output of __str__() in several places when it needs to display objects. Finally, note that __str__() is a good example of adding behavior to models. A Django model describes more than the database table layout for an object; it also describes any functionality that object knows how to do. __str__() is one example of such functionality \u2013 a model knows how to display itself.<\/p>\n<p>&nbsp;<\/p>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Once you\u2019ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell from within your virtual environment and typing the following: &nbsp;&gt;&gt;&gt; from books.models import Publisher &gt;&gt;&gt; p1 = Publisher(name=&#8217;Apress&#8217;, address=&#8217;2855 Telegraph Avenue&#8217;, &#8230; city=&#8217;Berkeley&#8217;, state_province=&#8217;CA&#8217;, country=&#8217;U.S.A.&#8217;, &#8230; website=&#8217;http:\/\/www.apress.com\/&#8217;) &gt;&gt;&gt; p1.save() &gt;&gt;&gt;&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8675],"class_list":["post-75311","page","type-page","status-publish","hentry","category-django-web-development","tag-basic-data-access"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Basic Data Access - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Basic Data Access - Tutorial\" \/>\n<meta property=\"og:description\" content=\"Once you\u2019ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell from within your virtual environment and typing the following: &nbsp;&gt;&gt;&gt; from books.models import Publisher &gt;&gt;&gt; p1 = Publisher(name=&#039;Apress&#039;, address=&#039;2855 Telegraph Avenue&#039;, ... city=&#039;Berkeley&#039;, state_province=&#039;CA&#039;, country=&#039;U.S.A.&#039;, ... website=&#039;http:\/\/www.apress.com\/&#039;) &gt;&gt;&gt; p1.save() &gt;&gt;&gt;...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:13+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/\",\"name\":\"Basic Data Access - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-18T08:47:57+00:00\",\"dateModified\":\"2024-04-12T08:47:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Basic Data Access\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Basic Data Access - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/","og_locale":"en_US","og_type":"article","og_title":"Basic Data Access - Tutorial","og_description":"Once you\u2019ve created a model, Django automatically provides a high-level Python API for working with those models. Try it out by running python manage.py shell from within your virtual environment and typing the following: &nbsp;&gt;&gt;&gt; from books.models import Publisher &gt;&gt;&gt; p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', ... city='Berkeley', state_province='CA', country='U.S.A.', ... website='http:\/\/www.apress.com\/') &gt;&gt;&gt; p1.save() &gt;&gt;&gt;...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:13+00:00","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/","name":"Basic Data Access - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-18T08:47:57+00:00","dateModified":"2024-04-12T08:47:13+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/basic-data-access\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Basic Data Access"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75311","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75311"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75311\/revisions"}],"predecessor-version":[{"id":83327,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75311\/revisions\/83327"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75311"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75311"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75311"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}