简体   繁体   中英

Having NULL as a primary key value

I would like to have an entity as follows:

class EntitySharedLinkPermission(models.Model):

    OFF = None
    COMPANY_VIEW = "Company View"
    COMPANY_EDIT = "Company Edit"
    PUBLIC_VIEW = "Public View"
    PUBLIC_EDIT = "Public Edit"

    name = models.CharField(max_length=12, primary_key=True)
    class Meta: db_table = 'entity_shared_link_permission'

However, I cannot have NULL as a primary key value here. What should I do here instead? One idea was to just remove the primary key on this table and have a unique key instead (no PK in the table) to get around this, but surely there must be a better solution.

Simply put, you can't have null as primary key column value. You should always supply non null value to the primary key. Also, don't go for unique, it just isn't the solution though it masquerades as being one. If you can't always supply non null value, introduce a new identity column to your table instead.

If you don't expect the list of items to change often, and the set is small, then it looks to me like you're trying to set up a "choices" field, for which Django already has nice support . Here's the example that the Django docs use, which you could easily adapt to your situation:

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

However, if you expect the list of permissions to be fluid and change often, you should consider making the permissions a Model of their own, and simply use a ForeignKey (or ManyToMany) relationship,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM