I have a model named Product
class Product(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
I am at Product views.py, how can I check if an attribute exist in the 'Order' model?
What I'm trying to do is this ->
hasattr(Product, "order__name")
CodePudding user response:
You can check if the target model has a name
attribute with:
hasattr(Product.order.field.related_model, 'name')
Here we thus access the ForeignKey
, and obtain a reference to the model it targets, in this case the Order
model, then we can check if that model has a name
attribute.
It is rather odd that a Product
however has a ForeignKey
to an Order
. Usually it is the other way around: an Order
has many "OrderLine
"s that then have a ForeignKey
to the Product
that these orderlines deal with.