您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

创建超级用户时创建日期行

创建超级用户时创建日期行

尝试将此功能用作信号处理程序:

def location_title(sender, instance, created, **kwargs):
    # Don't fire up on updates.
    if not created:
        return

    # Only handle new superusers.
    if not instance.is_superuser or not instance.is_active:
        return

    # Create a `Location` entry for new superuser.
    l = Location(user_id=instance.pk)
    l.save()

post_save.connect(location_title, sender=User)

向模型字段添加选择:

Django CharField有一个命名参数choices,可让您为最终用户提供可能值的列表,并以表格形式对其进行正确验证。可迭代的格式如下<internal_value>, <display_value>。将字段传递给choices参数后,您可以使用方法访问与其内部值相关的显示instance.get_<field_name>_display()

可迭代的选择可能如下所示:

class Location(models.Model):
    class Title:
        CLASSROOM = 'classroom'
        PLAYGROUND = 'playground'
        STAFF_ROOM = 'staff_room'

    TITLE_CHOICES = (
        (Title.CLASSROOM, 'Classroom'),
        (Title.PLAYGROUND, 'Playground'),
        (Title.STAFF_ROOM, 'Staff Room'),
    )

    user = models.ForeignKey(User,null=True)
    title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
    parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)

最终的解决方案如下:

class Location(models.Model):
    class Title:
        CLASSROOM = 'classroom'
        PLAYGROUND = 'playground'
        STAFF_ROOM = 'staff_room'

    BASE_LOCATION = Title.CLASSROOM

    TITLE_CHOICES = (
        (Title.CLASSROOM, 'Classroom'),
        (Title.PLAYGROUND, 'Playground'),
        (Title.STAFF_ROOM, 'Staff Room'),
    )

    user = models.ForeignKey(User,null=True)
    title = models.CharField('Incident Type', max_length=200,choices=TITLE_CHOICES,default=Title.CLASSROOM)
    parent_location_id = models.CharField('Parent Location', max_length=100, null=True, blank=True)
    is_active = models.BooleanField('Is Active', default=True)


def location_title(sender, instance, created, **kwargs):
    # Don't fire up on updates.
    if not created:
        return

    # Only handle new superusers.
    if not instance.is_superuser or not instance.is_active:
        return

    # Create a `Location` entry for new superuser.
    base = Location(user_id=instance.pk, title=Location.BASE_LOCATION)
    base.save()

    for value, _ in Location.TITLE_CHOICES:
        if value == Location.BASE_LOCATION:
            continue

        l = Location(user_id=instance.pk, title=value, parent_location_id=base.pk)
        l.save()

post_save.connect(location_title, sender=User)
其他 2022/1/1 18:29:36 有442人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶