

More Laziness with Foreign Keys
source link: https://alexgaynor.net/2008/nov/04/more-laziness-foreign-keys/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

More Laziness with Foreign Keys
Tue, Nov 4, 2008Yesterday we looked at building a form field to make the process of getting a ForeignKey to the User model more simple, and to provide us with some useful tools, like the manager. But this process can be generalized, and made more robust. First we want to have a lazy ForeignKey field for all models(be careful not to confuse the term lazy, here I use it to refer to the fact that I am a lazy person, not the fact that foreign keys are lazy loaded).
A more generic lazy foreign key field might look like:
from django.db.models import ForeignKey, Manager
class LazyForeignKey(ForeignKey):
def __init__(self, *args, **kwargs):
model = kwargs.get('to')
if model_name is None:
model = args[0]
try:
name = model._meta.object_name.lower()
except AttributeError:
name = model.split('.')[-1].lower()
self.manager_name = kwargs.pop('manager_name', 'for_%s' % name)
super(ForeignKey, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
super(ForeignKey, self).contribute_to_class(cls, name)
class MyManager(Manager):
def __call__(self2, obj):
return cls._default_manager.filter(**{self.name: obj})
cls.add_to_class(self.manager_name, MyManager())
As you can see, a lot of the code is the same as before. Most of the new code is in getting the mode’s name, either through _meta
, or through the last part of the string(i.e. User in “auth.User”). And now you will have a manager on your class, named either for_X where X is the name of the model the foreign key is to lowercase, or named whatever the kwarg manager_name is.
So if your model has this:
teacher = LazyForeignKey(Teacher)
You would be able to do:
MyModel.for_teacher(Teacher.objects.get(id=3))
That’s all for today. Since tonight is election night, tomorrow I’ll probably post about my application election-sim, and about PyGTK and PyProcessing(aka multiprocessing).
Recommend
-
42
Hello, Thanks for your hard work on gh-ost ! As I familiarize myself with the way it all works, I noted that foreign keys are
-
6
Rails ActiveRecord PostgreSQL Foreign Keys and Data Integrity Updated Jun 28, 2019 5 minute read
-
8
Lazy User Foreign Keys Mon, Nov 3, 2008A very common pattern in Django is for models to have a foreign key to django.contrib.auth.User for the owner(or submitter, or whatever other relation with User) and then to have...
-
12
Index on primary and foreign keys advertisements I have a database created with a GUI tool and I've noticed what appears to be an inconsistent use...
-
7
Foreign Keys, Blocking, and Update Conflicts Most databases should make use of foreign keys to enforce referential integrity (RI) wherever possible. However, there is more to this decision than...
-
5
...
-
4
In SQL, what are the differences between primary, foreign, and unique keys? The one thing that primary, unique, and foreign keys all have in common is the fact that each type of key can consist of more than just one column
-
6
Should I Create an Index on Foreign Keys in PostgreSQL? Back to the Blog Welcome to a weekly...
-
14
Carlos Zavala February 13, 2022 2 minute read Ho...
-
4
For Subscribers Hustle Culture 'Sucks' — But One Entrepreneur's 'Laziness Princi...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK