[Answered ]-How to see auto generated Primary Key of a model and to use it like FK in Django?

1👍

You can use an AutoField [Django-doc] with primary_key=True [Django-doc]:

from django.conf import settings


class Customer(models.Model):
    customer_id = AutoField(primary_key=True)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE
    )
    name = models.CharField(max_length=60)

    def __str__(self):
        return self.name


class Wallet(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    usd = models.FloatField(null=True)

For customer, it will make a column named customer_id with a foreign key to the primary key to the appname_customer table.

In the ModelAdmin of the wallet, you can use the raw_id_fields attribute [Django-doc] to use this to specify the primary key(s):

class WalletAdmin(admin.ModelAdmin):
    # …
    raw_id_fields = ('customer',)

Leave a comment