Перейти к содержимому

Related name django как использовать на примере

  • автор:

using related_name in Django

In this Blog we are going to talk about, How to use the related_name parameter in Django. When we create any type of relating in Django, Django by Default creates a backward relating or you can say it is a reverse relation. with the related_name attribute, we can give a name to the reverse relation.

Let’s try to understand this with an example:-

Exit fullscreen mode

in the upper model, we have one too many relations, a user can create as many notes as many he wants. Lets’ try to access all the notes of a currently logged-in user

Exit fullscreen mode

Here we directly access all the notes of currently logged-in users using the Notes model, now let’s say I don’t want to use the Notes model to access notes of currently logged-in users, I want to access Notes for the currently logged-in user using reverse relation. We already know that Django by default creates reverse relations and we can use that relationship with the _set object. Here we are trying to get all the notes of currently logged-in users.

Exit fullscreen mode

Here we can access all the todos of the currently logged-in users, using _set object.

Now let’s add the related_name attribute and see what changes and simplicity it provides.

Exit fullscreen mode

In the above code we have added related_name = «notes» parameter.

Exit fullscreen mode

As you can see using the related name attribute make our code more readable, you can use the related name attribute in all types of model relations in Django. If you want to disable Django’s default reverse relation then you can add related_name = “+” and this will disable Django’s default reverse relation.

Django Relationships¶

In this lecture we’ll learn a bit about the Django database ORM, how we interact with it, and how it allows us to deal with relationships between objects.

Users¶

We’ll start Django today using the shell management command:

$ python manage.py shell

What this means we can import any of the apps we have set up as being installed in our project.

This means in our Django shell we can import our profile model and the Django User model to play with them:

How do we query to see if we have any users in our DB? Remember, Django prefers to use the model Class object as the source for database interactions. Any model we create (or that is provided for us by Django) will have an objects attribute. That attribute is provided for us for free by Django. The value of the attribute is an instance of the ModelManager class from django.db.models .

So to get all of the User instances stored in our database we start with the User class object. We use the model manager objects and call the query api method all() on that: User.objects.all() .

We don’t have any users. Let’s make one:

What’s wrong with this? Our password is stored in cleartext. When you set a password directly on Django’s user object, it will store it in cleartext. Instead you should use .set_password() :

Now we have a hashed password. This is still a terrible password, but at least it’s not stored in cleartext. This will be important when you run tests, because Django’s authentication systems will be looking for a hashed password.

Bob still doesn’t have an id, because we never saved bob:

Relating Users to Profiles¶

Let’s check our ImagerProfile objects:

Bob has an ImagerProfile already. We talked before about how to hook up a connection that saves an ImagerProfile for a user automatically if it doesn’t already exist.

If we want to get the user bob’s profile we can do this:

Notice we’re not passing an id here. What is bob ? It’s a User object. We are asking our ImagerProfile to give us the profile object who’s user is this user object.

Look at our ImagerProfile definition:

ImagerProfile has a user attribute that is a OneToOneField that goes to User objects. That means we can use User objects directly as query values, and we can get back the profile we want. When working with an ORM, you should try always to think in terms of Python objects. Allow the ORM to handle figuring out how to get from the object to the ID that is actually stored in the database. That is its job.

These are all equivalent.

Relationships and Back References¶

Let’s look at our model again. Remember our relationships in SQLAlchemy? There was an argument we could use in a Relationship called back_populates . If we specified this value, then SQLAlchemy would add an attribute to the object at the other end of the relationship by that name. That attribute would reference the object from this end.

Django has the same thing. If you look above to our ImagerProfile definition, you will see related_name="profile" . When we use related_name , that means the User model at the opposite end of that relationship will have an attribute added to it that points back to this object. That means we should be able to ask bob for his profile , and get back an ImagerProfile object that corresponds to this user.

This is the Django way. All of our relationship fields will have this same kind of built in connection.

Let’s say you don’t want this to exist. Let’s remove it from our ImagerProfile :

How to use Related Name attribute in Django Model?

Prabhat Mishra

When we start using the Django model we can not understand all the features given by the Django in one shot. So today will try to understand the power of the related_name attribute.

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don’t specify a related_name, Django automatically creates one using the name of your model with the suffix _set.
Let’s start with an example and try to understand when you don’t use the realted_name attribute So that it will give you a clear picture.

Let’s try to understand the relationship between User, Post, and Comment as we do on a social media website.

One User can create many posts and for each post, there can be several comments and likes.

  1. User and Post have one to many relationships
  2. User and Like have many to many relationships
  3. Post and comment have one to Many relationships

Let’s create Django Models without realated_name and try to understand the relationship between User and Post.

After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command.

Let’s perform a simple query like how many posts belong to the first user in the Model.

So here you will get all the posts objects posted by first user

So as you can note here user.post_set is not more readable and meaningful, So if you want to increase the readability you must use related_name. now Let’s perform query with realated_name attribute.

Note: Before use you must add related_name attribute name in Foreign key, One to One, and Many to Many fields.

Now Let’s perform the query

1. How many post belongs to first user

It will return all post belongs to first user. you can see the proper use of realted_name attribute as its more readable than first_user.post_set.all()

2. Get all the post where first user have hit the like.

It will return all post where first user have hit the likes

3. Get all the comments for first post

It will return all the comments which belongs to first post

So the conclusion is whenever you are using foreign key, many to many or one to one relationships in Django you should use realted_name attribute.

Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site’s growth and development.

Understanding related_name in Django Models

Table of Contents

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the related model from the reverse side of the relation.

This attribute is particularly useful when working with many-to-many and foreign key relationships.

For example, consider the following models.

In this example, the Book model has a foreign key relationship with the Author model. By default, Django will use the lowercased model name of the related model to create the reverse relation. In this case, the reverse relation would be named author_set .

This means that you can access the books related to an author like this:

However, sometimes the default reverse relation name may not be clear or may clash with another attribute. To change the name of the reverse relation, you can use the related_name attribute in the ForeignKey field.

Here’s an example:

With this change, you can access the books related to an author using the books attribute:

Related Name with Many To Many Relationships

You can also use the related_name attribute when working with many-to-many relationships.

For example, let’s say you have the following models:

In this example, the Group model has a many-to-many relationship with the Person model. By default, the reverse relation would be named person_set . However, you can change the name of the reverse relation by using the related_name attribute.

With this change, you can access the groups related to a person using the member_of attribute:

In summary, related_name is an attribute that can be used to specify the name of the reverse relation in Django models and it’s an useful utility to write cleaner code.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *