简体   繁体   English

如何在Django中创建模型字段的动态选择

[英]How to create a dynamic choices of model field in django

class Task(models.Model):

    owner_set=set()
    for each in User.objects.all():
         owner_set.add((each.username,each.username))

    Owner = models.CharField(max_length=100,choices=owner_set)

In the code, i create a field by the choices of User, but this leads a problem: When i create a new user, the new username will not apprear in the filed of "Owner"; 在代码中,我根据用户的选择创建了一个字段,但这导致了一个问题:当我创建一个新用户时,新的用户名不会出现在“所有者”字段中; i need to restart the server. 我需要重新启动服务器。 So i want that the Owner filed should be dynamic, is there any way to do this? 所以我希望所有者字段应该是动态的,有没有办法做到这一点?

I don't want to use the Owner= models.ForeignKey(User,...) because may be i will use the names not only from the auth_user. 我不想使用Owner= models.ForeignKey(User,...)因为可能我将不仅使用auth_user使用名称。

Why would you store Owner as a CharField? 为什么将所有者存储为CharField? If it's a reference to a User object, it should be a ForeignKey. 如果是对User对象的引用,则应为ForeignKey。

Edit after comment Your data model seems broken. 评论后编辑您的数据模型似乎已损坏。 Nevertheless, if you really want to keep it as a CharField, you should not try to set the choices in the model at all. 但是,如果您确实希望将其保留为CharField,则完全不要尝试在模型中设置选择。 Define a custom form and either use a ModelChoiceField or set the choices in the form's __init__ method. 定义一个自定义表单,并使用ModelChoiceField或在表单的__init__方法中设置选择。

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

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