简体   繁体   English

将NULL作为主键值

[英]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. 但是,我不能在此处使用NULL作为主键值。 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. 一种想法是只删除该表上的主键,而改用一个唯一的键(表中没有PK)来解决此问题,但是肯定有更好的解决方案。

Simply put, you can't have null as primary key column value. 简而言之,您不能将null作为主键列值。 You should always supply non null value to the primary key. 您应该始终为主键提供非null值。 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. 如果不能总是提供非null值,请改为在表中引入一个新的标识列。

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 . 如果您不希望项目列表经常变化并且设置的项目很小,那么在我看来,您正在尝试设置“ choices”字段,Django已经对此提供了很好的支持 Here's the example that the Django docs use, which you could easily adapt to your situation: 这是Django文档使用的示例,您可以轻松地适应您的情况:

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, 但是,如果您希望权限列表是可变的并且经常更改,则应考虑将权限设为自己的模型,并只需使用ForeignKey(或ManyToMany)关系,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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