N
N
Neal Orven2019-06-17 14:50:49
Django
Neal Orven, 2019-06-17 14:50:49

I can't solve the problem. Slicing a list with an if else statement?

The essence of the question is this, I'm still a green pythonist, and help would not hurt me. There is an admin panel where the data goes through the foreign key relation ForeignKey. You need to write code like this, if the entry exceeds 50 characters, then + "..." is added to the list, if the list is less than 50 characters, then the ellipsis is not added.
1) Admin panel with available data output:
5d077dec4431e731681151.png
2) The task itself:
5d077e01d0c8d451747860.png
3) Code:

from django.db import models

class Topic(models.Model):
  text = models.CharField(max_length=200)
  date_added = models.DateTimeField(auto_now_add=True)

  def __str__(self):
    return self.text

class Entry(models.Model):
  topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
  text = models.TextField()
  date_added = models.DateTimeField(auto_now_add=True)

  class Meta:
    verbose_name_plural = 'entries'

  def __str__(self):
    return f"{self.text[:50]}..."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Bushmanov, 2019-06-17
@NealO

def __str__(self):
    return f"{self.text[:50]}..." if len(self.text) > 50 else self.text

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question