Issue
I have a model named Product
class Product(models.Model):
order = models.ForeignKey(Order, on_delete = models.CASCADE)
quantity = models.ForeignKey(Quantity, on_delete = models.CASCADE)
In both ForeignKey-s I have the same property named 'number'. I want to check if that property exists in Product model or in its ForeignKey-s models.
What I am trying to do is:
hasattr(Product, 'number')
Solution
Try this created a generic function:
def model_field_exists(model, field, check_related_fields=False):
if check_related_fields:
for field in model._meta.get_fields():
if field.is_relation and hasattr(field.related_model, field)
return True
return hasattr(model, field)
field = "number"
if model_field_exists(Product, field, check_related_fields=True):
print("{0} field exist.".format(field))
else:
print("{0} field does not exist.".format(field))
Answered By - Ahtisham
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.