create auto increment integer field in django

Viewed 56

i want to create auto increment integer field. I want to create an ID for each user. I am a beginner and please explain completely and clearly :) I want to automatically assign an ID to each user.

my Model:

from django.db import models
class User_account(models.Model):
    email = models.EmailField()
    fullname = models.CharField(max_length=30)
    username = models.CharField(max_length=20)
    password = models.CharField(max_length=30)
    marital_status = models.BooleanField(default=False)
    bio = models.CharField(default='' ,max_length=200)


def __str__(self):
    return f"(@{self.username}) {self.fullname}"

def save(self, *args, **kwargs):
    self.username = self.username.lower()
    self.email = self.email.lower()
    return super(User_account, self).save(*args, **kwargs)

my View:

from django.shortcuts import render
from .models import User_account

def profile(request, username):
    users = User_account.objects.all()
    for user in users:
        if username == user.username:
            return render(request, 'account_app/profile.html', context={"user_info":user})

def users_list(request):
    users = User_account.objects.all()
    return render(request, 'account_app/users_list.html', context={"user_info":users})
1 Answers

You did not specify a field with primary_key=True [Django-doc], this means that Django will automatically add a field to your model named id.

If you do not change the DEFAULT_AUTO_FIELD setting [Django-doc], or set the default_auto_field attribute [Django-doc] of the AppConfig of your app, it will use an AutoField [Django-doc] which is an IntegerField that will automatically add a value. You thus can access this with myuser.id or myuser.pk.

Please do not use loops to filter on the username, this will result in linear search in the Django/Python layer. It is better to filter the database with:

from django.shortcuts import get_object_or_404

def profile(request, username):
    user = get_object_or_404(User_account, username=username)
    return render(request, 'account_app/profile.html', context={'user_info': user})
Related