Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: a better way to write a if-then block with join?
    primarykey
    data
    text
    <p>Is there a better way to write this code? I know it's very simple, but the way I wrote it seems so repetitive.</p> <p>I'm not necessary looking for a one-line genius code, just some other readable, useful alternative.</p> <p>Thanks in advance!</p> <pre><code>def __unicode__( self ): location = [] if self.room != None: location.append( self.room ) if self.floor != None: location.append( self.floor ) if self.building != None: location.append( self.building ) location.append( self.property ) return ", ".join( location ) </code></pre> <p><code>self.property</code> is always set, which is not true for <code>self.room</code>, <code>self.floor</code>, and <code>self.building</code>. By the way, this is part of the <code>models.py</code> of a Django code in case anyone is wondering.</p> <p><em><strong>Side question</strong></em>: Is using <code>property</code> as a variable name a bad idea? I noticed <code>property</code> gets highlighted under syntax, but I looked it up and it's not a <a href="http://docs.python.org/reference/lexical_analysis.html#keywords" rel="nofollow">Python reserved word</a>.</p> <p>Here is the complete class:</p> <pre><code>class Location( models.Model ): def __unicode__( self ): location = [] if self.room != None: location.append( self.room ) if self.floor != None: location.append( self.floor ) if self.building != None: location.append( self.building ) location.append( self.property ) return ", ".join( location ) comments = models.TextField( blank = True ) room = models.CharField( max_length = 135, blank = True ) floor = models.CharField( max_length = 135, blank = True ) building = models.CharField( max_length = 135, blank = True ) property = models.ForeignKey( Property ) t_created = models.DateTimeField( auto_now_add = True ) t_modified = models.DateTimeField( auto_now = True ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload