I noticed that you can’t have -, +, /, *, or any other mathematical character symbol in the related_name. You also can’t use :, |, or ..
If you have any of the above characters in related_name, although Django’s models.py will validate, whenever you do a query lookup it’ll throw an error like
Q(userprofile.user__place__managers=user)
SyntaxError: keyword can't be an expression
The reason I want to use a special character is because I like to have my related_name in the form of {class_name}{field_name}. So for example for the UserProfile model class I would do something like
class UserProfile(models.Model)
user = models.OneToOneField(User, related_name='userprofile-user')
user_type = models.ManyToManyFields(UserType, related_name='userprofile-user_type')
That way when I do a query that involves a following a relationship backward, but still know how I am following it backward. For example, if I simply do
user_type = models.ManyToManyFields(UserType, related_name='user_type')
then I can access UserType from User doing User.objects.get(pk=1).user_type.all(). But this makes it looks like user_type is a field of User.
Instead if I could do something like User.objects.get(pk=1).userprofile-user_type.all() then I would know that I am going from User to UserProfile to UserType.
Well my way of thinking is probably in the minority and I would assume that most people would just do related_name='user_type' or maybe even use default user_type_set.
Another question would be: What is the good style for naming related_name?
userprofile-user_type is not a valid python identifier.
Python thinks you are trying to subtract user_type from userprofile.
In your specific case
profileswould be a good enough related manager name.So that when you have a a UserType instance:
It would give you all the profiles associated with that user type.
Also there is no ManyToManyField*s*, remove the “s”.
Try not to be more verbose than what is needed to convey the meaning of a relationship.
The field name inside the related name is redundant and unnecessary.
UPDATE:
Please do not name it
userprofiles_from_user_typeIt’s like having this:
Instead of:
Let me give you a more complex example with an intermediate table
Now let’s say we have people providing some kind of services to each other and I want
to know if the user “rantaplan” provides “tracking” service and to whom.
Note the PersonServicesRel the fields ‘provider’ and ‘consumer’ and their related_manager.
Also note the necessary query. I think it’s quite readable.
So I suggest that you name your fields and related managers depending on their purpose and usage, with as little verbosity as possible.