Home > Enterprise >  primary key for users
primary key for users

Time:01-01

primary key is created automatically for every row in table right, but for users isnt it better to use their username as primary key? or defaults better? or for posts like a music post or a picture shouldn't we use its name as primary key? if yes how should i change urls ? i mean this is my urlspath('genre_list/<int:pk>/',views.GenreDetailView.as_view(),name='genre_detail'),and path is int shoul i just remove int and let it be like <pk> or text primary key has another way?

CodePudding user response:

If I understood your question correctly, you would like to change your url from primary key (automatically assigned) to a custom slug (name/post-name/ etc)?

You should always keep primary key as the id, but if you would like to change it to something more unique than an integer, simply add this field to your model to override the basic int primary key:

id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

To customize your url and not use the id/pk, simply add this to your model:

models.py

from django.db import models
from django.urls import reverse
import uuid, string
from django.utils.text import slugify

class Post(models.Model):
    post_name = models.CharField(max_length=200, null=True, blank=True)
    post_topic = models.CharField(max_length=200, null=True, blank=True)
    slug = models.SlugField(null=True, unique=True, max_length=300)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
    
    def get_absolute_url(self):
        return reverse("post-page", kwargs={"slug": self.slug})
        
    def save(self, *args, **kwargs):
        self.slug = slugify(f"{self.post_name}-{self.post_topic}")
        return super().save(*args, **kwargs)

urls.py

path('post-page/<slug>/', views.post-page, name='post-page'),

This will return a url of:

www.example.com/post-name-post-topic

  • Related