Instantly share code, notes, and snippets.

Embed
What would you like to do?
from django.db import models
class LookupModel(models.Model):
id = models.CharField(max_length=30, primary_key=True)
class Meta:
abstract = True
@classmethod
def get_record(cls, pk):
attr = getattr(cls, pk.upper(), None)
if not attr:
attr = cls.objects.get(pk=pk)
return attr
def __str__(self):
return self.pk
def __hash__(self):
return hash(self.pk)
def __eq__(self, obj):
if not isinstance(obj, str):
return super().__eq__(obj)
return self.pk == obj
def __ne__(self, obj):
if not isinstance(obj, str):
return super().__ne__(obj)
return self.pk != obj
class LookupRecord:
def __init__(self, pk):
self.pk = pk
def __get__(self, instance, owner):
return owner.objects.get(pk=self.pk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment