2

Let's say I have the following Django model:

class Parent(models.Model):
    name = models.CharField(max_length=50)
    children = models.ManyToManyField("Child")

class Child(models.Model):
    name = models.CharField(max_length=50)

I have the Parent and Child models stored in variables in a script. Given these two models, how can I dynamically get the field name children as a string:

def get_field_name(model, related_model):
    # what do I need here

get_field_name(Parent, Child)
# "children"
Johnny Metz
  • 5,977
  • 18
  • 82
  • 146

2 Answers2

1

You can get the fields of a model and the type with this command

fields = Parent._meta.get_fields()

It gives tuple of all the models and <ManyToManyRel: parent.children> Now compare the class and if it has a many to many relation print the attribute. fields gives the class objects. Now you can get the type of the attribute by iterating over the tuple and printing the class name.

for i in fields:
     print(i.__class__name)

Now you can check for Many to Many field

SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
-1

You can try both of the following lines to get the fields of your model.

parent_fields = Parent._meta.fields
# or alternatively
parent_fields = Parent._meta.get_fields()

As you'll get a ImmutableList from the output, you'll have to get the field by index number to get the value as string something like that

parent_fields[1].attname
Eyakub
  • 3
  • 4