[Fixed]-Writing generic functions for all types of Django models

1👍

Try to use mixin.

def MixIn(pyClass, mixInClass):
    pyClass.__bases__ += (mixInClass,)

class Person(..sql model class..):
   ...
class Order(..sql model class..):


class MyMixinClass(object):
     def dummy(self):
        print("This method should be visible in Person and Order classes")

# apply mixin to Person and Order
MixIn(Person, MyMixinClass)
MixIn(Order, MyMixinClass)

p = Person()
p.dummy()  # it's ok

o = Order()
o.dummy()  # it's ok

Generally it would be nice to define another base class derived from ..sql model.. class.

class MyBaseModel(..sql model class..):
    def dummy(self):
       ...

class Person(MyBaseModel):
   ...

class Order(MyBaseModel):
   ....

You can give it a chance in Django, but in Pyramid and SQLAlchemy it doesn’t work for some reason (that is unknown to me), so I use simply dynamic MixIn function.

0👍

You can create a function in your models to increment by one all the foo like this:

class Task(models.Model):
    ....
    foo = ....

    def increment_foo(self):
        self.foo = self.foo + 1
        self.save()
        #increment by one all the foos
        Task.objects.filter(id__gt = self.id).update(foo = foo + 1)

class Animal(models.Model):
    ....
    foo = ....

    def increment_foo(self):
        self.foo = self.foo + 1
        self.save()
        #increment by one all the foos
        Animal.objects.filter(id__gt = self.id).update(foo = foo + 1)

you can call it in your view with: task_instance.increment_foo() or animal_instance.increment_foo()

Leave a comment