Django check related model and check field if exists in model


We can check if the field is related model in Model by :

1
model._meta.get_field("name_of_field").get_internal_type() == "ForeignKey"

Then we can check if the field name is exists in model by :

1
model._meta.get_field_by_name(_name)

Some example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if self.model._meta.get_field(field_name).get_internal_type() == "ForeignKey":
    # get related model
    # http://stackoverflow.com/questions/10347210/django-foreign-key-get-related-model
    related_model = self.model._meta.get_field(field_name).rel.to

    # Checking the default field for related model
    check_name = None
    for _name in [‘name’, ‘code’]:
        try:
            related_model._meta.get_field_by_name(_name)
        except FieldDoesNotExist:
            pass
        else:
            check_name = _name
            break

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.