1

I am creating a Django application, and during development I have created many classes which have a very similar structure, e.g.:

class OneAPIListView(generics.ListAPIView):
    queryset = models.One.objects.all()
    serializer_class = serializers.OneSerializer
    filter_class = OneFilterSet

class TwoAPIListView(generics.ListAPIView):
    queryset = models.Two.objects.all()
    serializer_class = serializers.TwoSerializer
    filter_class = TwoFilterSet

...
class <Name>APIListView(generics.ListAPIView):
    queryset = models.<Name>.objects.all()
    serializer_class = serializers.<Name>Serializer
    filter_class = <Name>FilterSet

I am wondering if there is a way to automatically generate these classes from the list of strings ["One", "Two", ..., <Name>]. I see that there are metaclasses in other SO questions like this, e.g. I could do something like

<Name> = type(<Name> + "APIListView", (generics.ListAPIView,), {'queryset' : ???})

But I am not sure what to put into ??? in my case since the variable is part of an object name.

3
  • Just put {'queryset': getattr(models, name).objects.all()} and so on. Commented Oct 20, 2017 at 18:08
  • By the way, this has nothing to do with metaclasses, which is a different thing. Though programmatic creation of classes that match some pattern could be considered metaprogramming. You could also in principle write a metaclass that does this but from your description there's no need for the extra complication that entails. Commented Oct 20, 2017 at 18:10
  • thank you, I did not know about getattr and it looks like it works well! Commented Oct 20, 2017 at 18:12

1 Answer 1

1

Just put {'queryset': getattr(models, name).objects.all()} and so on. getattr is important to know about if you're going to be doing any kind of metaprogramming. Occasionally setattr as well but less often, especially if you're just building classes with type(...).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.