Issue
I am facing an issue while trying to create a model that another model has a foreign key to and each time an instance is created in the model the model that has a relationship to the model needs to update as well but I don't think this is a good way to create relationships
class User(AbstractBaseUser, PermissionsMixin):
....
#three fields pointing to one model
owner = models.ManyToManyField(School, verbose_name=_(
"Ownes"), related_name='owner', blank=True)
workes_at = models.ForeignKey(School, verbose_name=_(
"Workes at"), related_name='Workes_at', on_delete=models.PROTECT, blank=True, null=True)
learns_at = models.ForeignKey(School, verbose_name=_(
"Learns at"), related_name='learns_at', on_delete=models.PROTECT, blank=True, null=True)
this way I have the issue I talked about above as when I want to create a school instance the owner would need to be set on the user model I also put the fields in the school model but that would mean when I want to filter users based on the schools they go to or own or work at, and also creating students or workers would be a hard task, I want to know what the recommended way to do this kind of stuff if maintaining 3 foreign key fields to the same model is not a good idea please recommend me another way, I have three types of user I have to handle in one model if that is not the best way tell me how are user types with different fields handled. thanks in advance.
Solution
You can make 1 model with foreign key to user with role:
class SchoolUser(AbstractBaseUser, PermissionsMixin):
SCHOOL_ROLES = (
("general", "General"),
("learn", "Learn"),
("owner", "Owner")
)
role = models.CharField(choices=SCHOOL_ROLES)
user = models.ForeignKey(User, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
user = User.objects.first()
school = School.objects.first()
school_user = SchoolUser()
school_user.user = user
school_user.school = school
school_user.role = 'learn'
school_user.save()
user = User.objects.first()
learns = user.schoooluser_set.filter(role='learn')
owners = user.schoooluser_set.filter(role='owner')
Answered By - vojtos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.