Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

python 3.x - base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute

The problem is this: I'm trying to replace the standard queryset:

queryset: MyModel.objects.all()

on my:

def get_queryset(self, username=None):
    if username is not None:
        user = UserModel.objects.get(username=username)
        queryset = MyModel.filter(author=user)
        return queryset
    else:
        queryset = MyModel.objects.all()
        return queryset

when I remove the "queryset", and leave only "get_queryset", an error appears:

AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.

All together looks so:

class MyModelView(viewsets.ModelViewSet):

permissions_classes = (permissions.IsAuthenticated,)
serializer_class = MyModelleSerializer

def get_queryset(self, username=None):
    if username is not None:
        user = UserModel.objects.get(username=username)
        queryset = MyModel.filter(author=user)
        return queryset
    else:
        queryset = MyModel.objects.all()
        return queryset

lookup_field = 'username'
lookup_value_regex = '[a-zA-Z0-9$&(._)-]+'

so How to override method correctly?

question from:https://stackoverflow.com/questions/48548622/base-name-argument-not-specified-and-could-not-automatically-determine-the-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the latest DRF, you need to explicitly set base_name in your viewset url if you don't have queryset defined.

So, something like this should do good:

router.register(r'my-model/', MyModelView, basename='MyModel')

See this: docs Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...