Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add non existing field name to django query

I’m trying to add extra field name base on its sub domains, but i cant do that, here is my views.py

def daily_vistors_detail_html(request):

    address = request.build_absolute_uri('/')
    host_name = address.partition('://')[2]
    sub_addr = host_name.partition('.')[0]
    hotel_name = 'hotel 1'
    if sub_addr == 'hotel 2':
        hotel_name = 'hotel 2'

    lists = MyModel.objects.annotate(hotel_name=hotel_name).order_by('-pk')
context = {
    'lists':lists
}

but it returns

QuerySet.annotate() received non-expression(s): hotel 1.
is there away to achieve that please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

thank you

>Solution :

I think what you search is the annotation of a Value.

# Import Value:
from django.db.models import Value

def daily_vistors_detail_html(request):

    address = request.build_absolute_uri('/')
    host_name = address.partition('://')[2]
    sub_addr = host_name.partition('.')[0]
    hotel_name = 'hotel 1'
    if sub_addr == 'hotel 2':
        hotel_name = 'hotel 2'

    # Annotate content of hotel_name as Value:
    lists = MyModel.objects.annotate(hotel_name=Value(hotel_name)).order_by('-pk')
context = {
    'lists':lists
}

You can find the docs here: Django Docs

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading