-2

I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tables they are FKs. The error I was getting was a conflict and needed to add a related_name. I need someone to explain to me the value for related_name. From my reading, it is showing the table name, If the FK is in the Comments model then the related_name='comments'. In my case I have three FK in the User model so how do I manage this?

I hope this tries to explain my query.

Isaac Hatilima
  • 151
  • 1
  • 10
  • 1
    Please suggest some meaningful title, SO is not only a place to solve immediate problems but to help future readers with their problems. – Sunderam Dubey Oct 21 '22 at 18:38
  • @SunderamDubey what would you rather the title be? – Isaac Hatilima Oct 21 '22 at 18:50
  • @StephenC the answer below is more understandable. The suggestion you gave was confusing because the related_name was map in a Map model. The below is clear enough. Thanks for the suggestion though. – Isaac Hatilima Oct 23 '22 at 09:15

1 Answers1

1

related_name is used for reverse relations..

an Example of one: from a District Object, I want to get all of the students in the distinct

districtObj.student_set.all()
# > Returns a list of Students

# format: {model}_set

Now you've got a conflict because student_set (the default) is taken, I'm not 100% why tbh, but it is.
Maybe someone smarter than me can explain..

Now that you know what you are setting, hopefully you can figure out a naming scheme..

Here's an Example: if you set Student.distinct's related name to 'students_in_district' you'd use it like:

districtObj.students_in_district.all()
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Nealium
  • 2,025
  • 1
  • 7
  • 9