Django detailview get_queryset and get_object - django

I am using Django detailview. initially, I used the URL pattern
url(r'^todo/details/(?P<pk>[\d]+)', views.todoDetailView.as_view(), name='detail_todo'),
my view is
class todoDetailView(DetailView):
model = models.todo
It worked fine.
In the second case, my URL is
url(r'^todo/details/(?P<id>[\d]+)', views.todoDetailView.as_view(), name='detail_todo'),
this time, I modified my view to
class todoDetailView(DetailView):
model = models.todo
# context_object_name = 'todo_detail'
def get_object(self, **kwargs):
print(kwargs)
return models.todo.objects.get(id=self.kwargs['id'])
It worked fine, I modified the second case to
class todoDetailView(DetailView):
model = models.todo
# context_object_name = 'todo_detail'
def get_queryset(self):
return models.todo.objects.get(id=self.kwargs['id'])
then I get an error,
Generic detail view todoDetailView must be called with either an object pk or a slug.
I know that there is no proper slug or pk provided. So, initially I added get_object() (it worked) but get_queryset() is not working. What is the difference in their working ??
And also if a user is getting details only based on the slug, I read on StackOverflow that
this can be used
slug_field = 'param_name'
slug_url_kwarg = 'param_name'
link - Generic detail view ProfileView must be called with either an object pk or a slug
Can anyone explain me actual working of get_object() and get_queryset() (also get_slug_field() if possible)
Along with the terms slug_field and slug_url_kwarg
Thanks in advance

get_object returns an object (an instance of your model), while get_queryset returns a QuerySet object mapping to a set of potentially multiple instances of your model. In the case of the DetailView (or in fact any class that inherits from the SingleObjectMixin, the purpose of the get_queryset is to restrict the set of objects from which you'll try to fetch your instance.
If you want to show details of an instance, you have to somehow tell Django how to fetch that instance. By default, as the error message indicates, Django calls the get_object method which looks for a pk or slug parameter in the URL. In your first example, where you had pk in the URL, Django managed to fetch your instance automatically, so everything worked fine. In your second example, you overrode the get_object method and manually used the id passed as parameter to fetch the object, which also worked. In the third example, however, you didn't provide a get_object method, so Django executed the default one. SingleObjectMixin's default get_object method didn't find either a pk or a slug, so it failed.
There are multiple ways to fix it:
1. Use pk in the URL
The simplest one is to simply use the code you provided in your first example. I don't know why you were unsatisfied with that, it is perfectly fine. If you're not happy, please explain why in more detail.
2. Override get_object
This is the second solution you provided. It is overkill because if you properly configured your view with the correct options (as you will see in the following alternatives), Django would take care of fetching the object for you.
3. Provide the pk_url_kwarg option
If you really want to use id in the URL for some reason, you can indicate that in your view by specifying the pk_url_kwarg option:
class todoDetailView(DetailView):
model = models.todo
pk_url_kwarg = 'id'
4. Provide the slug_field and slug_url_kwarg options [DON'T DO THIS]
This is a terrible solution because you are not really using a slug, but an id, but it should in theory work. You will basically "fool" Django into using the id field as if it was a slug. I am only mentioning it because you explicitly asked about these options in your question.
class todoDetailView(DetailView):
model = models.todo
slug_field = 'id'
slug_url_kwarg = 'id'
Regarding your get_queryset method: in your example, it doesn't even get to be executed, but in any case it is broken because it returns an individual object instead of a queryset (that's what objects.get does). My guess is you probably don't need a custom get_queryset method at all. This would be useful for example if you had a complex permission system in which different users can only access a different subset of todo objects, which I assume is not your case. Currently, if you provide this get_queryset method, even if everything else is configured properly, you will get an error. Probably an AttributeError saying that the queryset object has no attribute filter (because it will actually be a todo object and not a QuerySet object as Django expects).

The default get_object for DetailView tries to fetch the object using pk or slug from the URL. The simplest thing for you to do is to use (?P<pk>[\d]+) in the URL pattern.
When you override get_object, you are replacing this default behaviour, so you don't get any errors.
When you override get_queryset, Django first runs your get_queryset method an fetches the queryset. It then tries to fetch the object from that queryset using pk or slug, and you get an error because you are not using either of them.
The slug_field and slug_url_kwarg parameters are both defined in the docs. The slug_fields is the name of the field in the model used to fetch the item, and slug_url_kwarg is the name of the parameter in the URL pattern. In your case, you are fetching the object using the primary key (pk/id), so you shouldn't use either of these options.
For your URL pattern with (?P<id>[\d]+), you could use pk_url_kwarg = 'id'. That would tell Django to fetch the object using id from the URL. However, it's much simpler to use your first URL pattern with (?P<pk>[\d]+), then you don't have to override any of the methods/attributes above.

get_object() majorly uses with the generic views which takes pk or id
like: DetailView, UpdateView, DeleteView
where get_queryset() uses with the ListView where we are expecting more objects
Also, get_object() or self.get_object() uses pk as default lookup field or can use slug Field
a little peek at get_object()
if queryset is None:
queryset = self.get_queryset()
# Next, try looking up by primary key.
pk = self.kwargs.get(self.pk_url_kwarg)
slug = self.kwargs.get(self.slug_url_kwarg)
if pk is not None:
queryset = queryset.filter(pk=pk)
# Next, try looking up by slug.
if slug is not None and (pk is None or self.query_pk_and_slug):
slug_field = self.get_slug_field()
queryset = queryset.filter(**{slug_field: slug})

I can't help you with what the error message explicitly means, but get_queryset is used in listviews by get multiple objects, while get_object is used to get a single object (ie DetailView).
If you have a pk you can use to get an object, you don't need to specify a slug field. Slug field are used to filter out objects when you don't have or can't show the primary key publicly. This gives a better explanation of a slug field.

Related

How to read query string values in ModelViewSet logic?

I need to get at query string values in some viewset logic (in this case, derived from ModelViewSet). Everything I've read, including the Django REST Framework doc, says that request is an attribute of the viewset. But when I actually try to refer to it in code, no matter how I do so, I am shown the runtime error 'AddressViewSet' object has no attribute 'request' . Here's one simplified version of the class definition that triggers the error:
class AddressViewSet(viewsets.ModelViewSet):
def __init__(self, suffix, basename, detail):
attendee = ""
if self.request.query_params.get('attendee'):
attendee = self.request.query_params.get('attendee')
self.serializer_class = AddressSerializer
self.queryset = Address.objects.all()
How does one read request properties in viewset logic in DRF?
You are overriding the incorrect method. The ViewSet like all class based views in Django (All DRF views inherit from django.views.generic.View down the line) is instantiated (The pattern usually seen as View.as_view() internally creates an instance of the class) before the request is even received. This instance is used in the url patterns and when a request matching the url pattern is found a dynamically created function is called for the view which then calls dispatch.
Coming back to the point __init__ is not the correct method to override, if you want to filter the queryset you should instead be overriding get_queryset:
class AddressViewSet(viewsets.ModelViewSet):
queryset = Address.objects.all()
serializer_class = AddressSerializer
def get_queryset(self):
queryset = super().get_queryset()
attendee = ""
if self.request.query_params.get('attendee'):
attendee = self.request.query_params.get('attendee')
# Filter queryset here
return queryset
What I did not understand is that you can override a function get_queryset() but if you do that you do not assign queryset directly - that happens automatically. Once that overridden function is called the request is available as a property of the viewset, so it can be referred to there.

limit choices in drop downs in django rest browsable api

Is there a way to limit what fields are populated (such as in dropdown selectors or list selectors) in the DRF browsable API?
Below is an image example of how DRF is suggesting choices of "projects" to the user that he should select. However, the logged in user may or may not have access to these projects, so I'd like to get control over what shows up here! It seems that the default behavior is to show all related objects.
It would be really useful if there was a way to link the objects populated in these fields to be set according to a get_queryset() function.
This page seems to hint that it might be possible, I just can't find an example of how to do it: http://www.django-rest-framework.org/api-guide/filtering/
You can define a new field based on some of the serializers.RelatedField-ish classes, and use the request in the context to redefine what the method get_queryset returns.
An example that might work for you:
class AuthorRelatedField(serializers.HyperlinkedRelatedField):
def get_queryset(self):
if 'request' not in self.context:
return Author.objects.none()
request = self.context['request']
return Author.objects.filter(user__pk=request.user.pk)
class BookSerializer(serializers.HyperlinkedModelSerializer):
author = AuthorRelatedField(view_name='author-detail')
Check the templates in DRF/temapltes/rest_framework/inline/select.html. The select object in DRF uses the iter_options method of the field to limit the options in the select tag, which in turn uses the queryset from get_queryset.
This would efectively limit the options of the select tag used in the browsable API. You could filter as well in the get_choices method if you want to preserve the queryset (check the code in DRF/relations.py). I am unsure if this impacts the Admin.
I don't fully understand what do you want but try queryset filter's __in function if you need to show only exact values:
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
by filtering against a `username` query parameter in the URL.
"""
to_show = [ "user1", "user2", "user3"]
queryset = Purchase.objects.all()
username = self.request.query_params.get('username', None)
if username is not None:
queryset = queryset.filter(purchaser__username__in=username)
return queryset
you can add your values to to_show list and if queryset element equals one of them then it will be shown.
Also if you want to show only some fields of model you need to edit your Serializer's fields parameter:
class PurchaseList(serializers.ModelSerializer):
class Meta:
model = Purchase
fields = ('id', 'field1', 'field2', ...)

Overriding get_queryset in Django UpdateView. Why is it asking for <pk> or <slug> when I am returning the right queryset?

Here is my view.
class ModelxUpdateView(LoginRequiredMixin, UpdateView):
model = Modelx
template_name='template.html'
form_class = ModelxFormSet
def get_queryset(self):
# query_set = super(ModelxUpdateView, self).get_queryset().filter(user=self.request.user)
query_set = Modelx.objects.filter(user=self.request.user)
return query_set
The error that it's throwing is
AttributeError: Generic detail view ModelxUpdateView must be called with either an >object pk or a slug.
Could someone also clarify if editing multiple models is allowed via UpdateView? I mean if I am going to return a queryset, it's going to update each of the objects in that queryset right?
Could someone also clarify if editing multiple models is allowed via
UpdateView? I mean if I am going to return a queryset, it's going to
update each of the objects in that queryset right?
No, UpdateView is for a single object only. It inherits from the SingleObjectMixin which is why it needs a primary key to be passed in; as this primary key is used in the get_object method.
To do multiple object updates, try the UpdatesWithInlines view from the django-extra-views app.

Django: Managing urls like id:slug with duplicated slug

Using Django 1.5 I am storing the slug in DB
I configured my urls like follows:
url(r'^(?P<id>[0-9]+):(?P<slug>[-\w]+)$', TracksDetailView.as_view(), name="track-view"),
And in my podel I have:
#models.permalink
def get_absolute_url(self):
return ('track-view', [str(self.id), str(self.slug)])
If 2 slugs are the same I get the following error:
get() returned more than one GPXTrack -- it returned 2! Lookup parameters were {}
I use a generic view (DetailView) to render the page:
class TracksDetailView(DetailView):
model = GPXTrack
context_object_name = 'track'
Any idea on how to avoid this without needing unique slugs?
You are going to have to override your view's get_object method. The one you're inheriting does not take into account that you're using the ID and slug. It assumes you're passing either a pk or a slug - and also assumes they're unique.
The trick was simple but thanks for pointing me in the right direction!
Well the method get_object looks for a kwargs with key 'pk' rather than 'id', therefore I changed my urls to:
url(r'^(?P<pk>[0-9]+):(?P<slug>[-\w]+)$', TracksDetailView.as_view(), name="track-view"),
And everything worked fine!

Django custom manager with RelatedManager

There must be a problem with super(InviteManager, self).get_query_set() here but I don't know what to use. When I look through the RelatedManager of a user instance,
len(Invite.objects.by_email()) == len(user.invite_set.by_email())
Even if the user does not have any invites. However, user.invite_set.all() correctly returns all of the Invite objects that are keyed to the User object.
class InviteManager(models.Manager):
"""with this we can get the honed querysets like user.invite_set.rejected"""
use_for_related_fields = True
def by_email(self):
return super(InviteManager, self).get_query_set().exclude(email='')
class Invite(models.Model):
"""an invitation from a user to an email address"""
user = models.ForeignKey('auth.User', related_name='invite_set')
email = models.TextField(blank=True)
objects = InviteManager()
'''
u.invite_set.by_email() returns everything that Invite.objects.by_email() does
u.invite_set.all() properly filters Invites and returns only those where user=u
'''
You may want a custom QuerySet that implements a by_email filter. See examples on Subclassing Django QuerySets.
class InviteQuerySet(models.query.QuerySet):
def by_email(self):
return self.exclude(email='')
class InviteManager(models.Manager):
def get_query_set(self):
model = models.get_model('invite', 'Invite')
return InviteQuerySet(model)
Try:
def by_email(self):
return super(InviteManager, self).exclude(email='')
If nothing else, the .get_query_set() is redundant. In this case, it may be returning a whole new queryset rather than refining the current one.
The documentation specifies that you should not filter the queryset using get_query_set() when you replace the default manager for related sets.
Do not filter away any results in this type of manager subclass
One reason an automatic manager is used is to access objects that are related to from some other model. In those situations, Django has to be able to see all the objects for the model it is fetching, so that anything which is referred to can be retrieved.
If you override the get_query_set() method and filter out any rows, Django will return incorrect results. Don’t do that. A manager that filters results in get_query_set() is not appropriate for use as an automatic manager.
Try using .all() in place of .get_query_set(). That seemed to do the trick for a similar problem I was having.
def by_email(self):
return super(InviteManager, self).all().exclude(email='')