简体   繁体   中英

How to get object by name in views.py django

How to get object in views.py using name not by id.

def StockSummaryPage(request, title):
    stocks_data = get_object_or_404(Stock, string=title)
    return render(request, 'stocks/stock_summary_page.html', {'stocks_data':stocks_data})

This is my views.py and in

stocks_data = get_object_or_404(Stock, string=title)

we use pk= stock_id but i want to do it by title. So help me

You can get an object by any of its model fields.

Assuming you have a field called title in your Stock model and assuming you are passing the title to your view.

stocks_data = get_object_or_404(Stock, title=title)

Please be aware if you are getting an object by a field that is not unique you will get an error: get() returned more than one Model -- it returned 54!
In this case use get_list_or_404(Stock, title=title) which will return the result of .filter(). Django Shortcut Functions: get_list_or_404()

Here we assume that field as title .

1st method : using filter()

def StockSummaryPage(request, title):
    stocks_data = Stock.objects.filter(title=title)
    return render(request, 'stocks/stock_summary_page.html', {'stocks_data':stocks_data})

2nd method : using get_object_or_404

def StockSummaryPage(request, title):
    stocks_data = get_object_or_404(Stock, title=title)
    return render(request, 'stocks/stock_summary_page.html', {'stocks_data':stocks_data})

This can solve in another way also. I just found this way

def StockSummaryPage(request, title):
        context = {}
        # add the dictionary during initialization
        context["data"] = Stock.objects.get(title=title)

        return render(request, "stocks/stock_summary_page.html", context)

then you can get data in html using

data

keyword like

data.title
data.name

etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM