I am learning Django.
When I was learning how to use get_object_or_404
, I noticed that some codes specify id
as the argument of get_object_or_404
, while others specify pk
.
It seems that whether I specify id
or pk
, the result is the same.
foo1 = get_object_or_404(FooModel, pk=1)
foo2 = get_object_or_404(FooModel, id=1)
"""
FooModels table has some records that includes id is 1.
When I access foo/1, foo1 and foo2 have the same values.
"""
How do you use these parameters differently? Or if there is something fundamentally wrong with my thinking, please let me know.
Thanks.
models.py
from django.db import models
from django.utils import timezone
class FooModel(models.Model):
name = models.CharField('name', max_length=20)
body = models.CharField('body', max_length=100)
created_at = models.DateTimeField('created_at', default=timezone.now)
urls.py
from . import views
urlpatterns = [
path("foo/<int:id>", views.foo),
]
views.py
from django.shortcuts import get_object_or_404
from .models import FooModel
def foo(request, id)
foo1 = get_object_or_404(FooModel, pk=id)
foo2 = get_object_or_404(FooModel, id=id)
"""
FooModels table has some records that includes id is 1.
When I access foo/1, foo1 and foo2 have the same values.
"""
$ python -m django --version
2.2.20
$ python --version
Python 3.7.9