[Answer]-Filter across different models by one common field in django

1👍

First, to try to answer your question directly: given what you’ve described, I don’t know any way around checking each table. If you index on uuid that will certainly speed up the queries. Also, use exists() instead of count().

But the fact that uuid is unique across all tables might be a sign that you should reorganize your schema. If you can’t do away with the idea entirely, consider linking from your user model to a new model that specifies both the table and the primary key of the corresponding row.

Django has a built-in way of doing this: the contenttypes framework. From the documentation:

Adding a foreign key from one of your own models to ContentType allows your model
to effectively tie itself to another model class…. A normal ForeignKey can only
“point to” one other model…. The contenttypes application provides a special field
type (GenericForeignKey) which works around this and allows the relationship to be
with any model.

Leave a comment