why not able to see new column for full name?

Viewed 24

i am trying to concatinate values of f_n and l_n, display as fullname column, display the fullname values character length, and display fullname length less than 12, display names as ascending order

from django.db import models

class c1(models.Model):
    f_n=models.CharField(max_length=100)
    l_n=models.CharField(max_length=100)
    des=models.TextField()


python manage.py shell

In [1]: from django.db.models.functions import Concat

In [2]: from django.db.models import Value as V

In [3]: from temp1app.models import c1


In [4]:             
result=c1.objects.annotate(fullname=Concat('f_n',V('('),'l_n',V(')')))

In [5]: result
Out[5]: <QuerySet [<c1: c1 object (1)>, <c1: c1 object (2)>, <c1: c1     
object (3)>]>
1 Answers

You can implement the __str__ representation method like the following:

from django.db import models

class c1(models.Model):
    f_n=models.CharField(max_length=100)
    l_n=models.CharField(max_length=100)
    des=models.TextField()

    def __str__(self):
        return f'{self.f_n} {self.l_n}'

So in that way when you get a queryset like the following:

queryset = c1.objects.all()

If you print the queryset:

print(queryset)

You will be able to see the first name and last name.

If you really wanted to print the fullname property that you are creating with annotate, just do the following:

for i in result:
    i.fullname

Or you can do something like the following:

result.values_list('fullname', flat=True)

That will be like another property of your model.

Related