1
votes

I'd like to use two different primary keys in my DRF database app. By default Django "create" id as PK but when I'm trying to define new field in model (uuid = models.UUIDField (primary_key=True, default=uuid.uuid4, editable=False), default id field is not defined (in DB exist only uuid).

How can I initialize both of them?

I can mention that I didn't define id field in my model because it is (or should be - as I suppose) adding by DRF.

class Store(models.Model):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, 
editable=False)
    name = models.CharField(max_length=100, blank=False)
    url = models.URLField(max_length=300, blank=False)
    country = models.CharField(max_length=100, blank=True)
1
instead of setting primary_key as True set unique as True. That would be the standard way of having two unique fields. - 5parkp1ug
@5parkp1ug it's partly good solution because it works but i'd like to use uuid as foreign key in other model. Is it possible to connect e.g. Product (Model) field storeUUID = models.ForeignKey(Store) even if uuid isnt PK but only unique ? - Poul3R
your UUID field is unique you could always use to_field argument. Check this link - 5parkp1ug

1 Answers

1
votes

Primary key

In the relational model of databases, a primary key is a specific choice of a minimal set of attributes (columns) that uniquely specify a tuple (row) in a relation (table).

So, you can either use default primary key id or uuid (your choice).

If you want both then use unique=True instead.

class Store(models.Model):
  uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
  name = models.CharField(max_length=100, blank=False)
  url = models.URLField(max_length=300, blank=False)
  country = models.CharField(max_length=100, blank=True)

For your case you can change your model as

from django.db.models.fields import AutoField
from django.db.models.fields import checks
from django import models

class AutoFieldNonPrimary(AutoField):

    def _check_primary_key(self):
        if self.primary_key:
            return [
                checks.Error(
                    "AutoFieldNonPrimary must not set primary_key=True.",
                    obj=self,
                    id="fields.E100",
                )
            ]
        else:
            return []

class Store(models.Model):
      id = models.AutoFieldNonPrimary(unique=True)
      uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
      name = models.CharField(max_length=100, blank=False)
      url = models.URLField(max_length=300, blank=False)
      country = models.CharField(max_length=100, blank=True)