Jeremiah Rose
Jeremiah Rose

Reputation: 4132

Override Oscar models using other Oscar models from the same app

I need achieve something like this:

from oscar.apps.catalogue.abstract_models import AbstractProduct
from oscar.apps.catalogue.models import ProductClass

Product(AbstractProduct):
     @property
     display(self):
          if self.product_class = ProductClass.objects.get(pk=1):
               #do something
          else:
               #do something else

But when I do a from catalogue.models import Product elsewhere I invariably get the default Oscar Product and not my overridden Product with the display() property. I believe this is because the built-in Oscar Product is being registered before my custom one when I do the import ProductClass.

However to achieve the functionality I need it's vital I have access to ProductClass in the forked version of Product!

How can I get around this catch-22?

Upvotes: 0

Views: 463

Answers (1)

patrys
patrys

Reputation: 2769

When overriding Oscar models you need to move any non-abstract imports below the class definitions that are meant to replace models that come with Oscar. Here's an example.

In your case it should be safe to just move the models import below:

from oscar.apps.catalogue.abstract_models import AbstractProduct


Product(AbstractProduct):
    @property
    display(self):
        if self.product_class == ProductClass.objects.get(pk=1):
            #do something
        else:
            #do something else


from oscar.apps.catalogue.models import *

The display property will continue to work since by the time it is called for the first time, the module scope will already contain all the necessary models.

I've changed the import to * to make sure that all other models are loaded from Oscar.

Please note that the star import will inevitably try to import the Product model as well but Oscar will notice that a model by that name is already registered and will simply discard the other definition. It is ugly and confusing but that's the Oscar's recommended method.

Upvotes: 1

Related Questions