Andres
Andres

Reputation: 59

Identify what model belongs a unique field (primary key)

I would like with an unique field, to obtain the name of the model where it belongs. I was trying to use the get_model but it has another purpose.

Suppose that you have a school with multiple classrooms (each classroom is a model), and you wan to search a student with just the ID of him, receiving the name of the classroom where the student is.

So you type the ID (primary key) and the function will return you the class (model) where the student belong

Upvotes: 0

Views: 38

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

I would like with an unique field, to obtain the name of the model where it belongs.

To get the model, to which a field belongs, you can use the model attribute:

Returns the model on which the field is defined. If a field is defined on a superclass of a model, model will refer to the superclass, not the class of the instance.

The above will answer your question, but a bigger issue is with this:

Suppose that you have a school with multiple classrooms (each classroom is a model), and you wan to search a student with just the ID of him, receiving the name of the classroom where the student is.

This is not a sustainable model and will cause issues as each classroom means a new table. This structure will cause you problems when you are doing searches across classrooms.

The second issue is you are confusing the value of a field with the name of the field. A primary key (the id) is a value. You can search for values if you know what field there are in, if you want to retrieve a record with primary key value 1, you would write a query like this:

SELECT * FROM classroom_table WHERE id = 1

In Django, this is Classroom.objects.get(id=1)

You can't go the other way around, that is "find me the table, that has the value "1" in the field of id" which is what you are asking to do here.

You need to fix your database structure so that there is one model for students, and one model for classroom; and a student can belong to many classrooms:

class Student(models.Model):
   name = models.CharField(max_length=200)

class Classroom(models.Model):
   students = models.ManyToMany(Student)

Now you can do things like find all classrooms for a student with id 1:

student = Student.objects.get(id=1)
for room in student.classroom_set.all():
   print(room)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599550

This question isn't very clear.

If you have a Student model and a Classroom model, and there is a ForeignKey from Student to Classroom, then you need to get the student from the primary key:

student = Student.objects.get(pk=my_pk_value)

and then get its classroom:

student.classroom

Upvotes: 1

Related Questions