Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

How to create choice field in django model using another model

I have two models first User model and second Organization Model. Admin will be responsible for adding data in Organization Model.So I have used Foreign key.

class Organizaton(models.Model):
    name = models.CharField(max_length=255)
    status = models.BooleanField(default=True)
    created_by = models.ForeignKey(CustomUser,on_delete=models.CASCADE,limit_choices_to=    {'is_staff': True})
    created_date = models.DateTimeField(auto_now_add=True)

and I have a Custom User table where I want to store which user belongs to which Organization:

class CustomUser(AbstractUser): 

    organization_name = models.ForeignKey(Organization,on_delete = models.CASCADE)

If I declare CustomUser Class first, then there is an error inside CustomUser class in organization_name field that says class Organization is not Found or declared.

If I declare Organization Model class before CustomUser model class, then I'm getting an error inside the Organization class in created_by field saying CustomUser class not found or declared.

How can I solve this issue?

question from:https://stackoverflow.com/questions/65880812/how-to-create-choice-field-in-django-model-using-another-model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Declare your CustomUser first and change your ForeignKey to string like following:

class CustomUser(AbstractUser): 

    organization_name = models.ForeignKey('Organization', on_delete=models.CASCADE)

And it won't depend on declaration order anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...