我有一個名為 Product 的模型
class Product(models.Model):
order = models.ForeignKey(Order, on_delete = models.CASCADE)
quantity = models.ForeignKey(Quantity, on_delete = models.CASCADE)
在兩個 ForeignKey-s 中,我都有相同的屬性,名為“數字”。我想檢查該屬性是否存在于 Product 模型或其 ForeignKey-s 模型中。
我想做的是:
hasattr(Product, 'number')
uj5u.com熱心網友回復:
試試這個創建了一個通用函式:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394638.html
下一篇:無法安裝需求txt
