Do I need a ForeignKey for a Django user or profile model?

I wonder what people think about attaching models directly to the auth.User object and to the user profile model.

I store several different types of models that my user adds to my application. Application users will search for other users by criteria on these models.

On the one hand, I think that if I join directly to the user, then I will not need to do request.user.get_profile () every time I need to capture user entries, and this does not mean that the user always has a profile (they work in my application in mo, but still). This leads to the fact that the profile model simply contains the contact information of the user.

On the other hand, I believe that I will most likely need profile values ​​(e.g. name, location) when I search for these other models.

No doubt everything will work, so maybe that doesn't matter, but I just wondered what other people thought.

Thanks!

Ludo.

+6
source share
2 answers

I would also recommend creating foreign keys for the User model. It just simplifies your life when working with a user object in a single view. This way you can do things like request.user.foo_set, etc., without having to go through the profile model.

+2
source

In general: if you want to make your applications reusable, always create foreign keys for the User model.

As you said, in most cases you will need a user, as well as a profile instance, so use a cache to prevent multiple database queries.

If reuse does not matter, create a foreign key for the profile and use select_related () to get a user instance with one request.

+1
source

Source: https://habr.com/ru/post/900120/


All Articles