0

I have 2 classes defined like:

class Parent(models.Model)
    # class definition

And the second class:

class Child(models.Manager):
    def get_queryset(self):
        pass

Now I want to override the 'objects' of class Parent. Normally it will go like this:

class Parent():
    objects = Child()

But I can't modify class Parent because it's a third party library. Is there any workaround for this problem?

Kha Nguyễn
  • 463
  • 1
  • 4
  • 16
  • there is two **different** parent classes? – JPG Feb 27 '18 at 11:14
  • @JerinPeterGeorge No, there is only one Parent class. The Parent class below is how it's supposed to be modified. But since the Parent class is a third party library I cannot modify it – Kha Nguyễn Feb 27 '18 at 11:19
  • are you trying to **access** `child class object` from `parent class` ? – JPG Feb 27 '18 at 11:51
  • @JerinPeterGeorge No. The situation is like this question: https://stackoverflow.com/questions/14032329/django-extending-objects-manager-raises-nonetype-object-has-no-attribute-met. I however cannot change the Alpha class just like the answer does. – Kha Nguyễn Feb 27 '18 at 11:58

1 Answers1

0
setattr(Parent, 'objects', Child())

write this line in end of file where you have your manager class. this will override the objects attribute of Parent Class if exist or add objects attribute. Example:

from django.db import models

class abc(models.Model):
    pass


class pqr(models.Manager):
    def get_queryset(self, *args, **kwargs):
        print('in get_queryset')

setattr(abc, 'objects', pqr())

now in shell get or create object of parent class in this example abc class and perform any operation on in .

a = abc()
a.objects.all()

but this method is wrong it will override the objects attribute and if you want to use this method then use attribute name different than objects

Rohit Chopra
  • 567
  • 1
  • 8
  • 24