'How to print multiple object from table def __str__(self):return self.title
I created a article models below models.py
class Article(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
is_deleted = models.BooleanField(default=False)
custom_id = models.UUIDField(blank=False,null=False, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=200, blank=False)
text = models.TextField()
created_on = models.DateTimeField("created on", auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.title
for print the title object I Used below lines
def __str__(self):
return self.title
But I want to print the title object with user object.How will do? For Example
Title Name
Solution 1:[1]
You format it with the username (or some other field) with:
def __str__(self):
return f'{self.title} {self.user.username}'
or you can use the str(…)
implementation of the user with:
def __str__(self):
return f'{self.title} {self.user}'
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |