0

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
  • `pk` is a special parameter for django that refers to the primary key field on the model. By default, django assigns `id` as the primary key field for a model, but if you manually assign another field as the primary key, then `pk` will refer to that field. – Scratch'N'Purr Jun 22 '21 at 04:33
  • https://newbedev.com/django-queries-id-vs-pk – Kiran Jun 22 '21 at 04:35
  • @Scratch'N'Purr I could understand it well. Thanks for the clear answer! – onsenkoki Jun 22 '21 at 04:38
  • @KiranChauhan Thanks for the informative article! I'll take that as a reference. – onsenkoki Jun 22 '21 at 04:41

0 Answers0