"self.fields['field_name'].queryset" in Djano, can it be applied to a OneToOne field?
I'm new to Django and have been trying to wrap my head around OneToOne field relationship with _set.all()
My models.py
class User(AbstractUser):
is_admin = models.BooleanField(default=False)
is_employee = models.BooleanField(default=True)
is_manager = models.BooleanField(default=False)
is_assistant = models.BooleanField(default=False)
class Profile(models.Model):
profile = models.OneToOneField(User, on_delete=models.CASCADE)
class Manager(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
I'm trying to update a Manager instance and not quite sure why self.instance.user.profile_set.all()
keeps throwing an "'User' object has no attribute 'profile_set'" AttributeError in this section:
forms.py
elif self.instance.pk:
self.fields['user_profile'].queryset = self.instance.user.profile_set.all()
I hope my question is clear, any help would be greatly appreciated! Cheers!
You can access the related Profile
of a User
with:
myuser.profile
indeed, a OneToOneField
is in essence a ForeignKey
with a unique=True
constraint. This means that for a User
there is at most one related Profile
. The related_name=…
parameter [Django-doc] by default is the name of the class (here Profile
) in lowercase (so profile
). You can thus access the related Profile
with .profile
. It will raise an AttributeError
in case no such Profile
exists.
The modeling of manager however has redundant data: you do not need to specify both the User
and the Profile
, you can determine the other by the first. By introducing duplicate data, you make it possible that in the future Manager
s exist where the user
is updated, but the user_profile
is not and vice versa. If you need the profile
and you store the user
, you can access it with mymanager.user.profile
, and if you store the user_profile
, you can access it with mymanager.user_profile.user
. Storing both thus makes not much sense.
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.