Home > Enterprise >  Django: How to list or loop multiple classes .as_view() with very similar methods. (How to simplify
Django: How to list or loop multiple classes .as_view() with very similar methods. (How to simplify

Time:02-05

I have the following classes in views.py

class Base():
   def function:
      ***blah blah blah***
      return data # a list of data [data1, data2, data3, ...]

class JSONView1(Base,JSONBase)
   def get_data(self):
      json_data1 = list(Base().function()[0])
      return json_data1
   
class JSONView2(Base,JSONBase):
    def get_data(self):
        json_data2 = list(Base().function()[1])
        return json_data2

JSONView1 = JSONView1.as_view()
JSONView2 = JSONView2.as_view()

Mainly, in class Base I build a data list, then I create 2 classes, each one calling a specific data from class Base, e.g., JSONView1 calls data1 and JSONView2 calls data2. These JSON classes are important because they convert the data to a JSON script using JSONBase (no shown here for simplicity). Finally I use .as_view() in views.py because I will call them in urls.py.

The problem is that this is ok for 2 Views, but what if I have 5. I don't want to create a class for each new data in the list because the only difference between the classes is just the index, 0,1,2,3,.... the rest is the same

I would like to have something like

for k in range(5):
   class JSONView[k](Base,JSONClass)
   def get_data(self):
      json_data[k] = list(Base().function()[k])
      return json_data[k]
   JSONView[k] = JSONView[k].as_view()

Iterate over the code itself changing the index. I'm not an expert so an example to solve this would be thoroughly appreciated.

Regards

CodePudding user response:

You can pass an arg k to __init__ method and then use it in get_data method.

It will look kind of this:

class JSONView(...):
    def __init__(self, k, *args, **kwargs):
        self.k = k
        super(JSONView, self).__init__(*args, kwargs)

    def get_data(self):
        json_data = list(Base().function()[self.k])
        return json_data

CodePudding user response:

You can create classes with superclasses and an d give an attributedict (a key, attribute, and value, function or literal value.

See this example here:

https://python-course.eu/oop/dynamically-creating-classes-with-type.php

Because this is what you're asking to do, sorry I dont have time to apply it to your code, if you need more clarity than the link provides, send a message and I'll update this answer to give code examples as you've provided

  •  Tags:  
  • Related