Difference between attributes "related_name" and "related_query_name" in Django?

Can you explain the difference between attributes related_nameand related_query_nameobject Field in Django? When I use them, how to use them? Thanks!

+19
source share
3 answers

related_namewill be an attribute of a related object that will allow you to "return" to a model with a foreign key on it. For example, if it ModelAhas a field like:, model_b = ForeignKeyField(ModelB, related_name='model_as')this will allow you to access the instances ModelAthat are associated with your instance ModelBby clicking model_b_instance.model_as.all(). Note that this is usually written with the plural for the foreign key, because the foreign key is a one-to-many relationship, and many aspects of this equation are the model with the foreign key field declared in it.

A further explanation related to in the docs is helpful. https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects

related_query_name Django. , . - Model A, : model_b = ForeignKeyField(ModelB, related_query_name='model_a') model_a , : ModelB.objects.filter(model_a=whatever). related_query_name. , ( ) related_name related_query_name. .

+38
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

- , - . , ( ), (). Album_instance.artist, , Album_instanc, ( ).

Musician_instance.album_set.all() 

modelname_set.

, related_name, artist = models.ForeignKey(Musician, on_delete=models.CASCADE, related_name='back')

modelname_set (artist.set) back.

Musician_instance.back.all()

, Django , related_name "+" "+".

related_query_name

+1

See an example of a company employee for these two fields in this post https://simpleisbetterthancomplex.com/tips/2018/02/10/django-tip-22-designing-better-models.html

I find it the most concise and easy to digest

0
source

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


All Articles