Is there a better way to write this code? I know it’s very simple, but the way I wrote it seems so repetitive.
I’m not necessary looking for a one-line genius code, just some other readable, useful alternative.
Thanks in advance!
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 )
self.property is always set, which is not true for self.room, self.floor, and self.building. By the way, this is part of the models.py of a Django code in case anyone is wondering.
Side question: Is using property as a variable name a bad idea? I noticed property gets highlighted under syntax, but I looked it up and it’s not a Python reserved word.
Here is the complete class:
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 )
This first part was an answer to the original question if choosing the first non-None element to append. See updates below that address the revised question
Without trying to do a crazy one-line or something too fancy, I think this is a pretty easy solution. Just loop over them and append the first one that is not None, then break.
If you want a one-liner, here is a list comprehension:
A more readable compromise to that last one could be:
@tzaman was right in suggesting not to use
propertyfor your variable names. It is a built in type:Update
Because in your comments you mentioned what you actually wanted was any of those properties that are not None, its a super simple list comp:
Update 2: A great suggestion in the comments by @Vaughn Cato