Django database query: How to get object by id?

前端 未结 6 1517
遇见更好的自我
遇见更好的自我 2021-01-30 19:05

Django automatically creates an id field as primary key.

Now I need to get the object by this id.

object = Class.objects.filter() 

How

6条回答
  •  面向向阳花
    2021-01-30 19:48

    In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.

    Use example:

    def myFunc(request, my_pk):
        my_var = get_object_or_404(CLASS_NAME, pk=my_pk)
    

提交回复
热议问题