Skip to content

Instantly share code, notes, and snippets.

class Exclusion(models.Model):
Models a period of time we wish to exclude a particular student from being included in some data report.
student = models.ForeignKey(Student, on_delete=models.CASCADE)
start = models.DateField("exclusion_start")
end = models.DateField("exclusion_end")
active = models.BooleanField(verbose_name="Still send digital communications.", default=True)
def __str__(self):
data = instance.__dict__ # get the specific Student instance's symbol table
field_name = self.field.attname # pull out the field name (first name, in our case)
if data.get(field_name, self) is self:
# Let's see if the field is part of the parent chain. If so we
# might be able to reuse the already loaded value. Refs #18343.
val = self._check_parent_chain(instance) # check if this value is already pulled down from the db upstream
if val is None:
val = getattr(instance, field_name)
data[field_name] = val # set the student instance __dict__ key for future attribute lookups!
def __get__(self, instance, owner):
Instead of directly returning the value directory, we look up each instance's value using
the instance itself as the key.
if instance is not None: # attribute lookup initiated from instance
if len(self._instance_values) < NonNullStringDescriptor.CAPACITY:
self._instance_values[instance] = self.__default
return self._instance_values.get(instance, self.__default)
else: # attribute lookup initiated via class
from weakref import WeakKeyDictionary
class NonNullStringDescriptor:
CAPACITY = 2 # maximum of two instances can store their non-default attribute values here
def __init__(self, value: str = "Default Name"):
self._instance_values = WeakKeyDictionary()
self.__default = value
def __get__(self, instance, owner):
if __name__ == "__main__":
student = Person()
studentB = Person()
print( # Default Name
print( # Default Name = "Changed Name!!!"
print( # "Changed Name!!!"
print( # "Changed Name!!!"
def contribute_to_class(self, cls, name, private_only=False):
Register the field with the model class it belongs to.
If private_only is True, create a separate instance of this field
for every subclass of cls, even if cls is not an abstract model.
self.model = cls
cls._meta.add_field(self, private=private_only)
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
last_login = models.DateTimeField(_('last login'), blank=True, null=True)
is_active = True
# ....
def is_anonymous(self):
class property(object):
def __init__(self, fget: Optional[Callable[[Any], Any]] = ...,
fset: Optional[Callable[[Any, Any], None]] = ...,
fdel: Optional[Callable[[Any], None]] = ...,
doc: Optional[str] = ...) -> None: ...
def getter(self, fget: Callable[[Any], Any]) -> property: ...
def setter(self, fset: Callable[[Any, Any], None]) -> property: ...
def deleter(self, fdel: Callable[[Any], None]) -> property: ...
def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ...
def __set__(self, obj: Any, value: Any) -> None: ...
class StudentWithStaticProp:
def __init__(self):
self._name = "Default Name"
def _name(self):
return "A new name, never changes"
name = property(_name)
# both classes below implement Python properties using data descriptors
class StudentWithInlineProps:
def __init__(self, name="Default Name"):
self._name = name
# getting the values
def get_name(self):
print('Getting value')
return self._name