Answer the question
In order to leave comments, you need to log in
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:
2) The task itself:
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
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 questionAsk a Question
731 491 924 answers to any question