Django遗留数据库场景下,如何访问作为参数传入的模型属性?
Got it, let's break down how to fix that "not subscriptable" error you're seeing.
The core issue here is that Django model instances are objects, not dictionaries—so you can't use square bracket notation (obj['field_name']) to access their attributes like you would with a dict. Instead, Python gives us a built-in tool for exactly this scenario: the getattr() function.
How to Use getattr() for Dynamic Attribute Access
getattr() lets you retrieve an object's attribute using a string name, which is perfect for your case where field names vary across models. Here's how to implement it:
Basic Example
Suppose you have a function that needs to pull the registration number from any of your models, regardless of the field name:
def extract_registration_id(model_instance, field_name): # Use getattr to safely get the attribute # The third argument (None) is a default if the field doesn't exist return getattr(model_instance, field_name, None) # Usage with EURegister (uses 'reg_no') eu_record = EURegister.objects.first() eu_reg_id = extract_registration_id(eu_record, 'reg_no') # Usage with another model (e.g., uses 'registration_id') na_record = NARegister.objects.first() na_reg_id = extract_registration_id(na_record, 'registration_id')
Handling Uncertain Field Names
If you don't always know which field name a model uses, you can check for common options in sequence:
def get_reg_number(instance): # Try common registration field names possible_fields = ['reg_no', 'registration_id', 'reg_id', 'registration_number'] for field in possible_fields: if hasattr(instance, field): return getattr(instance, field) # Return a default or raise an error if no matching field is found return None
Why This Works Better Than __dict__
You might be tempted to use instance.__dict__[field_name], but getattr() is the safer choice:
- It respects Django's model properties and any custom attribute logic you might have.
- It lets you specify a default value to avoid
AttributeErrorif the field doesn't exist.
内容的提问来源于stack exchange,提问作者Indika Rajapaksha

