Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

How not to display a field when it's None in Django

I have this model:

class MsTune(models.Model):
    name = models.CharField(max_length=255) # title (source)
    start_page = models.CharField(max_length=20, blank=True, null=True, default=None)

def __str__(self):
        if not self.start_page or self.start_page != '' or self.start_page is not None or self.start_page is not "None" or self.start_page is not null:
            return '%s, %s' % (self.name, self.start_page)
        else:
            return '%s' % (self.name)

As you can see, I want only name if start_page is empty, or name, start_page if start_page is filled. No matter how many conditions I put (see above), I keep getting name, None in my template. What am I missing? Also, is there a shorter code I can put in place, instead of the verbose if / else ?

Edit

This is the content of my field in the database:

mysql> SELECT start_page from bassculture_mstune where id = 1942;
+------------+
| start_page |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)

And in Django's shell:

>>> mytune = MsTune.objects.get(id=1942)
>>> print(mytune.start_page)
None
question from:https://stackoverflow.com/questions/65936912/how-not-to-display-a-field-when-its-none-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As default value is going to be "" as from your field, simply checking not value should work:

def __str__(self):
    returnVal = f"{self.name}"
    if self.start_page:
        returnVal = f"{returnVal}, {self.start_page}"
    return returnVal

Or, you can use ternery operation:

def __str__(self):
    return self.start_page and f"{self.name}, {self.start_page}" or f"{self.name}" 

Python ternary operation: Refs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...