Y
Y
Yura Khlyan2019-04-10 19:25:23
Django
Yura Khlyan, 2019-04-10 19:25:23

Dynamic filter on Django?

Good day.
I have a "main" model:

class MainProcedure(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    procedure_id = models.CharField(max_length=32)
    method_type = models.CharField(max_length=100)
    owner = models.CharField(max_length=255)

    def __str__(self):
        return f'<MainProcedure (id={self.id.hex})>'

    @property
    def specific_procedure(self):
        return getattr(self, f'{self.method_type}_procedure')

And other models can be attached to it in applications (like O2O). For example:
class FooProcedure(AbstractProcedure):
    main_procedure = models.OneToOneField(MainProcedure, on_delete=models.CASCADE, related_name='foo_procedure')

    class Meta(AbstractProcedure.Meta):
        abstract = False

The essence is that the User can create procedures of different types, but to get them in one place. Everything is OK with the listing, but when it comes to filtering, I have a dilemma how to do it right. For example, if I want to filter by a titlespecific procedure, then I need to do something like this:
q = Q(foo_procedure__title__icontains='title') | Q(bar_procedure__title__icontains='title')
return qs.filter(q)

But what if there are more applications with their own types? Is it possible to somehow "dynamically" filter? What other options are there?
P.S. The option to rewrite the data structure is the last one to apply.
I will be very grateful for your help.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question