Always use defensive programming techniques when handling potentially null or empty values to avoid runtime errors. Consider these practices: 1. Use specialized methods when checking for default values or null states rather than direct comparisons:
Always use defensive programming techniques when handling potentially null or empty values to avoid runtime errors. Consider these practices:
if self.has_default(): # handle default case
if self.default and self.default is not NOT_PROVIDED: # handle default case
2. Use `getattr()` with a default value when accessing attributes that might be None:
```python
# Safer approach
on_delete = getattr(field.remote_field, "on_delete", None)
# Instead of directly accessing which might raise AttributeError
# on_delete = field.remote_field.on_delete # Risky if field.remote_field is None
if objs and (order_wrt := self.model._meta.order_with_respect_to): # process objects
4. Be aware of different types of nulls in specialized contexts (e.g., SQL NULL vs JSON null):
```python
# SQL NULL
obj.json_field = None
# JSON null (different semantics in queries)
obj.json_field = Value(None, output_field=JSONField())
These defensive patterns prevent common null-related errors and make code more robust.
Enter the URL of a public GitHub repository