{"id":75312,"date":"2020-01-18T14:18:07","date_gmt":"2020-01-18T08:48:07","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75312"},"modified":"2024-04-12T14:17:13","modified_gmt":"2024-04-12T08:47:13","slug":"adding-model-string-representations","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/","title":{"rendered":"Adding Model String Representations"},"content":{"rendered":"<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 style=\"margin-left: 18.0pt; tab-stops: 36.0pt;\"><span lang=\"EN-US\">&lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt;<\/span><\/pre>\n<p>We can fix this easily by adding a method called __str__() to our Publisher object. A __str__() method tells Python how to display the \u201cstring\u201d 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<\/pre>\n<pre>class 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 class=\"VSKILLbodytext\"><span lang=\"EN-US\">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:<\/span><\/p>\n<pre class=\"VSKILLbodytext\"><span lang=\"EN-US\">\u00a0<\/span><span lang=\"EN-US\">TypeError: __str__ returned non-string (type int).<\/span><\/pre>\n<p class=\"VSKILLbodytext\"><span lang=\"EN-US\">\u00a0<\/span><span lang=\"EN-US\">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:<\/span><\/p>\n<pre class=\"VSKILLbodytext\"><span lang=\"EN-US\">\u00a0\u00a0 <\/span><span lang=\"EN-US\">&gt;&gt;&gt; from books.models import Publisher<\/span><\/pre>\n<pre style=\"margin-left: 18.0pt; tab-stops: 36.0pt;\"><span lang=\"EN-US\">&gt;&gt;&gt; publisher_list = Publisher.objects.all()<\/span><\/pre>\n<pre style=\"margin-left: 18.0pt; tab-stops: 36.0pt;\"><span lang=\"EN-US\">&gt;&gt;&gt; publisher_list<\/span><\/pre>\n<pre style=\"margin-left: 18.0pt; tab-stops: 36.0pt;\"><span lang=\"EN-US\">&lt;QuerySet [&lt;Publisher: Apress&gt;, &lt;Publisher: O'Reilly&gt;]&gt;<\/span><\/pre>\n<p class=\"VSKILLbodytext\"><span lang=\"EN-US\">\u00a0<\/span><span lang=\"EN-US\">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.<\/span><\/p>\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noopener noreferrer\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<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: &lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt; We can fix this easily by adding a method called __str__() to our Publisher object. A __str__() method tells Python how to display&#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":[8676],"class_list":["post-75312","page","type-page","status-publish","hentry","category-django-web-development","tag-adding-model-string-representations"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Adding Model String Representations - 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\/adding-model-string-representations\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Adding Model String Representations - Tutorial\" \/>\n<meta property=\"og:description\" content=\"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: &lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt; We can fix this easily by adding a method called __str__() to our Publisher object. A __str__() method tells Python how to display...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/\" \/>\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=\"2 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\/adding-model-string-representations\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/\",\"name\":\"Adding Model String Representations - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-18T08:48:07+00:00\",\"dateModified\":\"2024-04-12T08:47:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Adding Model String Representations\"}]},{\"@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":"Adding Model String Representations - 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\/adding-model-string-representations\/","og_locale":"en_US","og_type":"article","og_title":"Adding Model String Representations - Tutorial","og_description":"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: &lt;QuerySet [&lt;Publisher: Publisher object&gt;, &lt;Publisher: Publisher object&gt;]&gt; We can fix this easily by adding a method called __str__() to our Publisher object. A __str__() method tells Python how to display...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/","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":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/","name":"Adding Model String Representations - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-18T08:48:07+00:00","dateModified":"2024-04-12T08:47:13+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/adding-model-string-representations\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Adding Model String Representations"}]},{"@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\/75312","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=75312"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75312\/revisions"}],"predecessor-version":[{"id":83336,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75312\/revisions\/83336"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75312"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75312"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75312"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}