0

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

4
  • 1
    Show Stock model. Commented Sep 16, 2020 at 8:30
  • here's Django docshow to make DB queries, more specifically you'll need to use method called filter() (eg. Stock.objects.filter(string=title) Commented Sep 16, 2020 at 8:34
  • Whats wrong with get_object_or_404(Stock, string=title) ? Commented Sep 16, 2020 at 8:38
  • @ArakkalAbu string=title is not working, we can write title=title Commented Sep 16, 2020 at 14:30

3 Answers 3

2

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()

Sign up to request clarification or add additional context in comments.

Comments

1

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})

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.