André
André

Reputation: 25554

Django - How to use a custom class in a view?

I've coded some classes in pure python, but now I need to use that classes in a django view.

my_custom_classes.py

class RetryException(Exception):
   ...
   ...

class Trade():
   def __init__(self):
       ...
       ...

   def some_other(self, id):
       ...
       ...

For example I need to make a call to a django model inside the "some_other(self, id)".

What is the best way of organizing this custom classes for using in a Django view?

Best Regards,

Upvotes: 5

Views: 2275

Answers (1)

dm03514
dm03514

Reputation: 55952

There is no difference between using a python class in a django view and using a class inside a "normal" python function.

Instantiate your class, and call its methods.

Do you have a Trade model? If so, would it makes sense to put that functionality in the Trade model class?

If you need to call something inside of your Trade class, what you are calling has to be in scope. If you are querying a model you can import it in the module Trade is defined in, and you can access it as you expect.

from yourproject.yourapp.models import AModel

class Trade(object):
    def some_other(self, id):
         return AModel.objects.filter(pk=id)

Upvotes: 1

Related Questions