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', ...)
Related
I have the following custom model manager in Django that is meant to count the number of related comments and add them to the objects query set:
class PublicationManager(models.Manager):
def with_counts(self):
return self.annotate(
count_comments=Coalesce(models.Count('comment'), 0)
)
Adding this manager to the model does not automatically add the extra field in DRF. In my API view, I found a way to retrieve the count_comments field by overriding the get function such as:
class PublicationDetails(generics.RetrieveUpdateAPIView):
queryset = Publication.objects.with_counts()
...
def get(self, request, pk):
queryset = self.get_queryset()
serializer = self.serializer_class(queryset.get(id=pk))
data = {**serializer.data}
data['count_comments'] = queryset.get(id=pk).count_comments
return Response(data)
This works for a single instance, but when I try to apply this to a paginated list view using pagination_class, overriding the get method seems to remove pagination functionality (i.e. I get a list of results instead of the usual page object with previous, next, etc.). This leads me to believe I'm doing something wrong: should I be adding the custom manager's extra field to the serializer instead? I'm not sure how to proceed given that I'm using a model serializer. Should I be using a basic serializer?
Update
As it turns out, I was using the model manager all wrong. I didn't understand the idea of table-level functionality when what I really wanted was row-level functionality to count the number of comments related to a single instance. I am now using a custom get_paginated_response method with Comment.objects.filter(publication=publication).count().
Original answer
I ended up solving this problem by creating a custom pagination class and overriding the get_paginated_response method.
class PaginationPublication(pagination.PageNumberPagination):
def get_paginated_response(self, data):
for item in data:
publication = Publication.objects.with_counts().get(id=item['id'])
item['count_comments'] = publication.count_comments
return super().get_paginated_response(data)
Not sure it's the most efficient solution, but it works!
I'll be as straightforward as possible:
I have a Challenge model, which holds information about a certain challenge and the amount of scores it gives. Any User can have multiple Submissions for a given challenge.
When querying for a specific Challenge, I want to return JSON with the Challenge's information along with the maximum score that the current request.user has scored. Is there a way to somehow ducktype (attach) the value to the model instance and serialize it with a given Serializer class?
What I've found is that ModelSerializer requires the model to have that field itself, where in my case I add it dynamically.
What's a good approach to this problem and has anybody had any similar problems?
this can be done by accessing the request.user in the serializer from extra context.
In generic views the model serializer is provided with extra context. This context has the request object.
you can define a method field on your Challenge serializer
class ChallengeSerializer(serializers.ModelSerializer):
user_max_score = serializers.SerializerMethodField()
class Meta:
model = Challenge
fields = '__all__'
def get_user_max_score(self, obj):
user_max_score = 0
request = self.context.get('request', None)
if request:
user = request.user
# get the user's max score
...
return user_max_score
You can provide extra context too if you are not using generic views. Read more here: http://www.django-rest-framework.org/api-guide/serializers/#including-extra-context
One of my Django admin "edit object" pages started loading very slowly because of a ForeignKey on another object there that has a lot of instances. Is there a way I could tell Django to render the field, but not send any options, because I'm going to pull them via AJAX based on a choice in another SelectBox?
You can set the queryset of that ModelChoiceField to empty in your ModelForm.
class MyAdminForm(forms.ModelForm):
def __init__(self):
self.fields['MY_MODEL_CHOIE_FIELD'].queryset = RelatedModel.objects.empty()
class Meta:
model = MyModel
fields = [...]
I think you can try raw_id_fields
By default, Django’s admin uses a select-box interface () for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.
raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField
Or you need to create a custom admin form
MY_CHOICES = (
('', '---------'),
)
class MyAdminForm(forms.ModelForm):
my_field = forms.ChoiceField(choices=MY_CHOICES)
class Meta:
model = MyModel
fields = [...]
class MyAdmin(admin.ModelAdmin):
form = MyAdminForm
Neither of the other answers worked for me, so I read Django's internals and tried on my own:
class EmptySelectWidget(Select):
"""
A class that behaves like Select from django.forms.widgets, but doesn't
display any options other than the empty and selected ones. The remaining
ones can be pulled via AJAX in order to perform chaining and save
bandwidth and time on page generation.
To use it, specify the widget as described here in "Overriding the
default fields":
https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/
This class is related to the following StackOverflow problem:
> One of my Django admin "edit object" pages started loading very slowly
> because of a ForeignKey on another object there that has a lot of
> instances. Is there a way I could tell Django to render the field, but
> not send any options, because I'm going to pull them via AJAX based on
> a choice in another SelectBox?
Source: http://stackoverflow.com/q/37327422/1091116
"""
def render_options(self, *args, **kwargs):
# copy the choices so that we don't risk affecting validation by
# references (I hadn't checked if this works without this trick)
choices_copy = self.choices
self.choices = [('', '---------'), ]
ret = super(EmptySelectWidget, self).render_options(*args, **kwargs)
self.choices = choices_copy
return ret
I have an order model with a followed_by field:
class order(models.Model):
followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"})
I have several such models and forms for those models. By default the form displays a modelchoicefield listing users that are mangers. This is fine. But the display isn't nice: it gives the username, and I want first+last name. This would work nicely: Change Django ModelChoiceField to show users' full names rather than usernames
except that now in everyform I must declare the queryset to limit users to managers. Can I use the above method so that the custom modelchoicefield defaults to my filtered queryset. so then from a form I can just say:
followed_by = ManagerUserModelChoiceField()
Can you define the queryset on your ModelChoiceField child class?
class UserModelChoiceField(ModelChoiceField):
# Query that returns set of valid choices
queryset = User.objects.filter(group__name='Managers')
def label_from_instance(self, obj):
return obj.get_full_name()
Try passing in the queryset as an argument to the ManagerUserModelChoiceField class.
followed_by = ModelChoiceField(queryset = User.objects.filter(groups__name="Managers")
After my comment to #Enrico this thought occurred to me: I overwrote the "init" class on my custom field like so:
class UserModelChoiceField(forms.ModelChoiceField):
def __init__(self, *args, **kwargs):
super(UserModelChoiceField, self).__init__(queryset=User.objects.filter(groups__name="Managers"), *args, **kwargs)
I've seen stuff like this done in python before but I'm new to python so I'm not sure if this is a bad thing to do or if I should make this better somehow? I'd appreciate some feedback. That being said, it seems to be working correctly.
I currently have a model set up like so:
I have a Test class with a foreign key to a custom UserProfile class. This property is called student. So each UserProfile may have taken more than one Test. Then in turn, each UserProfile is tied to a User by the typical onetoone relation. Another level of complexity is added because I have declared two user groups tutors and students. And the UserProfile class has a ManyToMany relation on to itself labeled "tutors". The logic is that each student may have many tutors teaching him. Now what I would like to do is add filters on the right-hand side of the Test admin page that lets you filter by the student and filter by tutor as well. setting list_filter = ('student',) simply lists all available UserProfiles. But this would include the UserProfiles which are tied to tutors as well. Obviously I would like to filter this list down to only students, because clearly filtering by any of these tutors would result in an empty queryset. I would then like to do a similar thing with filtering by tutor, where in this case the shorthand would be list_filter = ('student__tutors'), but I'd want this UserProfile set to be filtered down to only include those where user_groups_name='tutors'. What is the best way to do this?
For clarity, my object model looks like this:
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True,related_name='profile')
tutors = models.ManyToManyField("self",related_name="students")
class Test(models.Model):
student = models.ForeignKey(UserProfile,related_name='tests')
I tried subclassing django.contrib.admin.SimpleListFilter with the following:
class StudentListFilter(SimpleListFilter):
title = 'student'
parameter_name = 'student__id__exact'
def lookups(self, request, model_admin):
qs = model_admin.queryset(request)
return User.objects.filter(profile__id__in=qs.values_list('student__id')).extra(select={'full_name':'first_name||" "||last_name'}).values_list('profile__id','full_name')
def queryset(self, request, queryset):
if self.value() is not None:
return queryset.filter(student__id__exact=self.value())
else:
return queryset
Which seems to work for the first list_filter, but the trouble is for some reason there's a bug now where the selected option does not get highlighted in the custom filter. Only 'All' highlights but not the custom options. Here is an example of it that another user posted:
http://imgur.com/lyrYk
I am currently using the development version of django 1.4, so I'm not sure if this issue is tied to that or not.
Interesting problem.
I think you need to convert your lookups to a string.
return [(str(x), y) for x, y in your_valuesqueryset]
Line 98 on django.admin.filters defines the selected filter as:
'selected': self.value() == lookup
Where the lookup is populated directly from the results of the lookups method.
The auto type coercion in your filter() call is making the filter succeed but '2' != 2