django-model-utils icon indicating copy to clipboard operation
django-model-utils copied to clipboard

Does django-model-utils support querying an abstract base class?

Open specialorange opened this issue 6 years ago • 2 comments

Problem (help wanted)

I am trying to understand how to query an abstract base class/model via a unique model field (guaranteed unique by each end concrete model sharing the same unique_together clause(s) ). I have read in several sites that django-model-utils is the recommended solution, but from reading the docs and trying, it appears this is only true for Multiple Table Inheritance. Is it possible to use django-model-utils for abstract base class querying in any way?

Environment

  • Django Model Utils version: 3.1.2
  • Django version: 2.1
  • Python version: 3.5 and 3.6
  • Other libraries used, if any: none to my knowledge that involve the model classes outside of native django

Code examples

// models.py

from model_utils.managers import InheritanceManager

class Asset(models.Model):
    asset_id = models.CharField(max_length=100, editable=False)  # argua3y4tv9yqawnqv29…
    asset_name = models.CharField(max_length=200, editable=False)  # 10101
    account = models.ForeignKey(Account, on_delete=models.CASCADE)
    objects = InheritanceManager()

    class Meta(object):
        abstract = True

class B(Asset):  # intermediate abstract class
    pass

    class Meta(object):
        abstract = True

class C(B):
    unique_feature = models.CharField(max_length=200)
    class Meta(object):
        unique_together = (('asset_id', 'account'))
    

// urls.py

    url(r'^accounts/(?P<slug>[a-zA-Z]+)/assets/(?P<assetName>[a-zA-Z0-9]+)',
        AssetsViewSet.as_view({'get': 'retrieve'})),

// views.py (from a DRF viewset)

class AssetsViewSet(viewsets.ModelViewSet):
    serializer_class = AssetSerializer
    permission_classes = (permissions.IsAuthenticated, IsOrganizationMember,)


    def retrieve(self, request, slug=None, assetName=None):
        /regardless if I filter by the asset's account foregin key
        queryset = Asset.objects.filter(asset_name=assetName).select_subclasses()

This gives me the error:

AttributeError at /api/v1/accounts/FSL/assets/10101 Manager isn't available; Asset is abstract

Give code example that demonstrates the issue, or even better, write new tests that fails because of that issue.

specialorange avatar Oct 16 '18 19:10 specialorange

I don't know how to label this as help-wanted. I thought I could once I submitted it... :\

specialorange avatar Oct 16 '18 19:10 specialorange

@specialorange From what I figured, the InheritanceManager can only be used when dealing with non-abstract models. (Since it uses the onetoone field that is not there if you do abstract inheritance.)

Eraldo avatar Feb 28 '23 11:02 Eraldo