Update Model Instance via Django REST POST - python

I've got a model "Assignment" that I want to be able to update through the api.
Updated per comments
urls.py
router = routers.DefaultRouter()
router.register(r'assignments', views.AssignmentList, base_name='Assignments')
urlpatterns = [
url(r'^api/v1/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
serializers.py
class AssignmentSerializer(serializers.ModelSerializer):
class Meta:
model = Assignment
fields = (
'id', 'company', 'farm', 'sensor', 'name', 'location', 'notes', 'units', 'max_height', 'frequency',
'interval', 'max_threshold', 'min_threshold', 'notify', 'last_alert_time', 'last_alert_water_level')
views.py
class AssignmentList(viewsets.ModelViewSet):
serializer_class = AssignmentSerializer
pagination_class = None
def get_queryset(self):
queryset = Assignment.objects.all()
company_id = self.request.query_params.get('company_id', None)
sensor_id = self.request.query_params.get('sensor_id', None)
if company_id is not None:
queryset = Assignment.objects.filter(company_id=company_id)
if sensor_id is not None:
queryset = Assignment.objects.filter(sensor_id=sensor_id)
return queryset
Currently my view allows for easy filtering based on two of the fields, 'company_id' and 'sensor_id'. This allows for easy access of the data in json. Unfortunately I can't figure out how to POST back even with the built in API form. I would like to be able to filter down to a single instance and edit a single field, let's say "assignment.name" for now.
It's my understanding that...
The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). (DRF Docs)
So what do I need to do to leverage them to edit a model instance via url? Or honestly just edit one period. I've been running in circles trying different Mixins, views (UpdateAPIView, RetrieveUpdateAPIView etc.) and this question in particular Stack Overflow: Django Rest Framework update field.

Why you're lacking the required foreign key fields is entirely the question.
The reason is that presumably your fields are called company, farm and sensor, not company_id etc. Because the underlying database fields are called company_id and so on, DRF detects them as read-only properties on the model and so allows you to specify those names in the fields tuple without showing an error, but doesn't display the field in the browsable API. Change the fields tuple to include the actual names of the Django fields.
Note also that since you're using HyperlinkedModelSerializer, DRF it expects a linked ViewSet for those related models. If you don't have those defined, chnage it to a basic ModelSerializer.

Related

How do I correctly add the HyperlinkedRelatedField field to the serializer?

I want to make it possible for a json that gives all the model instances to go to a particular instance using the additional url field in the serializer.
There is a view to display the list
class DocumentsListView(viewsets.ViewSetMixin, generics.ListCreateAPIView):
user = serializers.PrimaryKeyRelatedField(read_only=True,)
queryset = Documents.objects.all()
serializer_class = DocumentsSerializer
permission_classes = []
def perform_create(self, serializer):
serializer.save(author=self.request.user)
urls.py
router = DefaultRouter()
router.register('', DocumentsListView)
urlpatterns = [
url('', include(router.urls), name='files')
]
serializers.py
class DocumentsSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedRelatedField(view_name='documents-detail')
class Meta:
model = Documents
fields = ('id', 'filename', 'datafile', 'type', 'created', 'url')
but got an error
'Relational field must provide a `queryset` argument, '
AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`.
If I set read_only='True', it works, but url didnt displayed
I've also tried this way of implementing serializer
class DocumentsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Documents
fields = ('id', 'filename', 'datafile', 'type', 'created', 'url')
but got an error
Could not resolve URL for hyperlinked relationship using view name "doctype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field
Recall that every view has a serializer set in serializer_class, and your serializer has a Meta class where you set a model, and thats how you reference the model type you're relating to in HyperLinkedRelatedField. The view_name field is the name of that model followed by '-list' if the url you request does not end with an id(for example when making POST requests), and '-detail' if it does.
Don't know if you eventually solved it but I also experienced something similar, and the solution was changing the HyperlinkedRelatedField to an HyperlinkedIdentityField.

Django admin: Prefetch choices in list_editable

I have a model Domain and I set it's ForeignKey Language model in list_editable in ModelAdmin.
The problem is that it causes lot of SQL queries according to django_debug_toolbar. I thought that I could solve it using select_related but it did not help because it selects only actual values, not all choices.
#register(Domain)
class DomainAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'main_url', 'language', 'max_depth', 'number_of_urls']
list_editable = ['name', 'main_url', 'language', 'max_depth']
list_select_related = ['language']
#def get_queryset(self, request):
# return super(DomainAdmin, self).get_queryset(request).prefetch_related('language')
It still perform SQL query for every Domain to fetch all Language objects.
How to make it fetch once for all Domains?
Django-cachalot is especially efficient in the Django administration website since it’s unfortunately badly optimised (use foreign keys in list_editable if you need to be convinced).
https://django-cachalot.readthedocs.io/en/latest/introduction.html

Limiting choices in foreign key dropdown in Django using Generic Views ( CreateView )

I've two models:
First one:
class A(models.Model):
a_user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE)
a_title = models.CharField("A title", max_length=500)
Second one:
class B(models.Model):
b_a = models.ForeignKey(A, verbose_name=('A'), unique=False, on_delete=models.CASCADE)
b_details = models.TextField()
Now, I'm using CreateView to create form for Value filling :
class B_Create(CreateView):
model = B
fields = ['b_a','b_details']
Then using this to render these field in templates.
Now, my problem is, while giving the field b_a ( which is the dropdown ), it list downs all the values of model A, but the need is to list only the values of model A which belongs to the particular logged in user, in the dropdown.
I've seen all the answers, but still not able to solve the problem.
The things I've tried:
limit_choices_to in models : Not able to pass the value of A in the limit_choices
form_valid : Don't have the model A in the CreateView, as only B is reffered model in B_Create
passing primary key of A in templates via url : Then there is no instance of A in the template so can't access. Also, don't want to handle it in templates.
I'm new to Django and still learning, so don't know to override admin form.
Please suggest the implemented way, if possible to the problem. I've researched and tried most of the similar questions with no result for my particular problem. I feel like, this is a dumb question to ask, but I'm stuck here, so need help.
Thanks..
(Please feel free to suggest corrections.)
You have access to self.request.user in the form_valid of the view. But in order to limit the choices in the form you have to customize the form before it is served initially. You best override the view's get_form and set the form field's queryset:
class B_Create(CreateView):
model = B
fields = ['b_a','b_details']
def get_form(self, *args, **kwargs):
form = super(B_Create, self).get_form(*args, **kwargs)
form.fields['b_a'].queryset = self.request.user.a_set.all()
# form.fields['b_a'].queryset = A.objects.filter(a_user=self.request.user)
return form
Generally, there are three places where you can influence the choices of a ModelChoiceField:
If the choices need no runtime knowledge of your data, user, or form instance, and are the same in every context where a modelform might be used, you can set limit_choices_to on the ForeignKey field itself; as module level code, this is evaluated once at module import time. The according query will be built and executed every time a form is rendered.
If the choices need no runtime knowledge, but might be different in different forms, you can use custom ModelForms and set the queryset in the field definition of the respective form field.
If the queryset needs any runtime information, you can either override the __init__ of a custom form and pass it any information it needs to set the field's queryset or you just modify the queryset on the form after it is created which often is a quicker fix and django's default views provide nice hooks to do that (see the code above).
The #schwobaseggl answer is excellent.
Here is a Python 3 version. I needed to limit the projects dropdown input based on the logged-in user.
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
template_name = 'brand/product-create.html'
fields = '__all__'
def get_form(self, form_class=None):
form = super().get_form(form_class=None)
form.fields['project'].queryset = form.fields['project'].queryset.filter(owner_id=self.request.user.id)
return form

Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"

I am building a project in Django Rest Framework where users can login to view their wine cellar.
My ModelViewSets were working just fine and all of a sudden I get this frustrating error:
Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
The traceback shows:
[12/Dec/2013 18:35:29] "GET /bottles/ HTTP/1.1" 500 76677
Internal Server Error: /bottles/
Traceback (most recent call last):
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/viewsets.py", line 78, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 399, in dispatch
response = self.handle_exception(exc)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 396, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/mixins.py", line 96, in list
return Response(serializer.data)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 535, in data
self._data = [self.to_native(item) for item in obj]
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 325, in to_native
value = field.field_to_native(obj, field_name)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 153, in field_to_native
return self.to_native(value)
File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 452, in to_native
raise Exception(msg % view_name)
Exception: Could not resolve URL for hyperlinked relationship using view
name "user-detail". You may have failed to include the related model in
your API, or incorrectly configured the `lookup_field` attribute on this
field.
I have a custom email user model and the bottle model in models.py is:
class Bottle(models.Model):
wine = models.ForeignKey(Wine, null=False)
user = models.ForeignKey(User, null=False, related_name='bottles')
My serializers:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'password', 'is_superuser')
My views:
class BottleViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows bottles to be viewed or edited.
"""
queryset = Bottle.objects.all()
serializer_class = BottleSerializer
class UserViewSet(ListCreateAPIView):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
and finally the url:
router = routers.DefaultRouter()
router.register(r'bottles', views.BottleViewSet, base_name='bottles')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
# ...
I don't have a user detail view and I don't see where this issue could come from. Any ideas?
Thanks
Because it's a HyperlinkedModelSerializer your serializer is trying to resolve the URL for the related User on your Bottle.
As you don't have the user detail view it can't do this. Hence the exception.
Would not just registering the UserViewSet with the router solve your issue?
You could define the user field on your BottleSerializer to explicitly use the UserSerializer rather than trying to resolve the URL. See the serializer docs on dealing with nested objects for that.
I came across this error too and solved it as follows:
The reason is I forgot giving "**-detail" (view_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view.
There is one app in my project, suppose that my project name is myproject, and the app name is myapp.
There is two urls.py file, one is myproject/urls.py and the other is myapp/urls.py. I give the app a namespace in myproject/urls.py, just like:
url(r'', include(myapp.urls, namespace="myapp")),
I registered the rest framework routers in myapp/urls.py, and then got this error.
My solution was to provide url with namespace explicitly:
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail")
class Meta:
model = User
fields = ('url', 'username')
And it solved my problem.
Maybe someone can have a look at this : http://www.django-rest-framework.org/api-guide/routers/
If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. For example:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
]
you'd need to include a parameter such as view_name='api:user-detail' for serializer fields hyperlinked to the user detail view.
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:user-detail")
class Meta:
model = User
fields = ('url', 'username')
Another nasty mistake that causes this error is having the base_name unnecessarily defined in your urls.py. For example:
router.register(r'{pathname}', views.{ViewName}ViewSet, base_name='pathname')
This will cause the error noted above. Get that base_name outta there and get back to a working API. The code below would fix the error. Hooray!
router.register(r'{pathname}', views.{ViewName}ViewSet)
However, you probably didn't just arbitrarily add the base_name, you might have done it because you defined a custom def get_queryset() for the View and so Django mandates that you add the base_name. In this case you'll need to explicitly define the 'url' as a HyperlinkedIdentityField for the serializer in question. Notice we are defining this HyperlinkedIdentityField ON THE SERIALIZER of the view that is throwing the error. If my error were "Could not resolve URL for hyperlinked relationship using view name "study-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field." I could fix this with the following code.
My ModelViewSet (the custom get_queryset is why I had to add the base_name to the router.register() in the first place):
class StudyViewSet(viewsets.ModelViewSet):
serializer_class = StudySerializer
'''custom get_queryset'''
def get_queryset(self):
queryset = Study.objects.all()
return queryset
My router registration for this ModelViewSet in urls.py:
router.register(r'studies', views.StudyViewSet, base_name='studies')
AND HERE'S WHERE THE MONEY IS! Then I could solve it like so:
class StudySerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="studies-detail")
class Meta:
model = Study
fields = ('url', 'name', 'active', 'created',
'time_zone', 'user', 'surveys')
Yep. You have to explicitly define this HyperlinkedIdentityField on itself for it to work. And you need to make sure that the view_name defined on the HyperlinkedIdentityField is the same as you defined on the base_name in urls.py with a '-detail' added after it.
This code should work, too.
class BottleSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = Bottle
fields = ('url', 'wine', 'user')
Today, I got the same error and below changes rescue me.
Change
class BottleSerializer(serializers.HyperlinkedModelSerializer):
to:
class BottleSerializer(serializers.ModelSerializer):
I ran into this error after adding namespace to my url
url('api/v2/', include('api.urls', namespace='v2')),
and adding app_name to my urls.py
I resolved this by specifying NamespaceVersioning for my rest framework api in settings.py of my project
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning'}
TL;DR: It may be as simple as removing a trailing 's' from the router basename. No need to define a url field in your serializer.
For the original poster, the issue was resolved simply by registering the UserViewSet, as suggested in the top answer.
However, if anyone else has this issue even with all ViewSets registered, I think I've figured out what's going wrong, and I've found a solution that's cleaner than a lot of the others here.
In my case, I encountered this issue after trying to create a ViewSet with a custom get_queryset() function. When I replaced the ViewSet's queryset field with a custom get_queryset() function, I was then hit with this error:
AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
So, of course, I went to urls.py and modified my registration to include a basename as such:
router.register(r'messages', MessageViewSet, basename='messages')
But then I was hit with this error (as we see in the original post):
Could not resolve URL for hyperlinked relationship using view name "message-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
After reading the DRF docs on routers, I learned that the router automatically generates two url patterns for you, which have names:
'basename-list'
'basename-detail'
Because I set my basename='messages' (note the 's' at the end), my url patterns were named:
'messages-list'
'messages-detail'
Since DRF was looking a url pattern named 'message-detail' (note here the lack of 's'), I realized that I could resolve this simply by removing the trailing 's' from my basename as such:
router.register(r'messages', MessageViewSet, basename='message')
My final serializer and ViewSet implementations were as simple as this!
class MessageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Message
fields = ['url', 'message', 'timestamp', 'sender', ...]
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
def get_queryset(self):
return Message.objects.filter(...)
It appears that HyperlinkedModelSerializer do not agree with having a path namespace. In my application I made two changes.
# rootapp/urls.py
urlpatterns = [
# path('api/', include('izzi.api.urls', namespace='api'))
path('api/', include('izzi.api.urls')) # removed namespace
]
In the imported urls file
# app/urls.py
app_name = 'api' // removed the app_name
Hope this helps.
Same Error, but different reason:
I define a custom user model, nothing new field:
from django.contrib.auth.models import (AbstractUser)
class CustomUser(AbstractUser):
"""
custom user, reference below example
https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py
# original User class has all I need
# Just add __str__, not rewrite other field
- id
- username
- password
- email
- is_active
- date_joined
- method, email_user
"""
def __str__(self):
return self.username
This is my view function:
from rest_framework import permissions
from rest_framework import viewsets
from .models import (CustomUser)
class UserViewSet(viewsets.ModelViewSet):
permission_classes = (permissions.AllowAny,)
serializer_class = UserSerializer
def get_queryset(self):
queryset = CustomUser.objects.filter(id=self.request.user.id)
if self.request.user.is_superuser:
queryset = CustomUser.objects.all()
return queryset
Since I didn't give queryset directly in UserViewSet, I have to set base_name when I register this viewset. This is where my error message caused by urls.py file:
from myapp.views import (UserViewSet)
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='customuser') # <--base_name needs to be 'customuser' instead of 'user'
You need a base_name same as your model name - customuser.
If you're extending the GenericViewSet and ListModelMixin classes, and have the same error when adding the url field in the list view, it's because you're not defining the detail view. Be sure you're extending the RetrieveModelMixin mixin:
class UserViewSet (mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
A bit late but in Django 3 and above, include doesn't support namespace without specifying the app_name. Checking the source code for include, we see that the condition
if namespaces and not app_name:
....
is checked. And still from the source code, app_name is gotten like;
urlconf_module, app_name = arg
where arg is the first argument of the include. This tells us that, our include should be defined as
include((app.urls, app_name), namespace='...')
Example
Say you have a project myproject and an app myapp. Then you want to establish an address. You should use a viewset and define a router as below
myapp.urls
router.register('address', exampleviewset, basename='address')
myproject.urls
path('api/v1/', include(('myapp.urls', 'myapp'), namespace='myapp')),
serializers.py
class AddressSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:address-detail")
class Meta:
model = Address
fields = ('url',...)
Apparently, we can't use fields='__all__'. We must include url explicitly and list the remaining fields we need.
I ran into the same error while I was following the DRF quickstart guide
http://www.django-rest-framework.org/tutorial/quickstart/ and then attempting to browse to /users. I've done this setup many times before without problems.
My solution was not in the code but in replacing the database.
The difference between this install and the others before was when I created the local database.
This time I ran my
./manage.py migrate
./manage.py createsuperuser
immediately after running
virtualenv venv
. venv/bin/activate
pip install django
pip install djangorestframework
Instead of the exact order listed in the guide.
I suspected something wasn't properly created in the DB. I didn't care about my dev db so I deleted it and ran the ./manage.py migrate command once more, created a super user, browsed to /users and the error was gone.
Something was problematic with the order of operations in which I configured DRF and the db.
If you are using sqlite and are able to test changing to a fresh DB then it's worth an attempt before you go dissecting all of your code.
Bottle = serializers.PrimaryKeyRelatedField(read_only=True)
read_only allows you to represent the field without having to link it to another view of the model.
I got that error on DRF 3.7.7 when a slug value was empty (equals to '') in the database.
I ran into this same issue and resolved it by adding generics.RetrieveAPIView as a base class to my viewset.
I was stuck in this error for almost 2 hours:
ImproperlyConfigured at /api_users/users/1/
Could not resolve URL for hyperlinked relationship using view name "users-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
When I finally get the solution but I don't understand why, so my code is:
#models.py
class Users(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, blank=False, null=False)
email = models.EmailField(null=False, blank=False)
class Meta:
verbose_name = "Usuario"
verbose_name_plural = "Usuarios"
def __str__(self):
return str(self.name)
#serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Users
fields = (
'id',
'url',
'name',
'email',
'description',
'active',
'age',
'some_date',
'timestamp',
)
#views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = Users.objects.all()
serializer_class = UserSerializer
#urls_api.py
router = routers.DefaultRouter()
router.register(r'users',UserViewSet, base_name='users')
urlpatterns = [
url(r'^', include(router.urls)),
]
but in my main URLs, it was:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls', namespace='api')),
]
So to finally I resolve the problem erasing namespace:
urlpatterns = [
url(r'^admin/', admin.site.urls),
#api users
url(r'^api_users/', include('usersApi.users_urls')),
]
And I finally resolve my problem, so any one can let me know why, bests.
If you omit the fields 'id' and 'url' from your serializer you won't have any problem. You can access to the posts by using the id that is returned in the json object anyways, which it makes it even easier to implement your frontend.
I had the same problem , I think you should check your
get_absolute_url
object model's method input value (**kwargs) title.
and use exact field name in lookup_field
It is worth noting that if you create an action with detail=False (typo?) then this errors will be raised, replace it with detail=True:
#action(detail=True)
...
I wanted to stay with everything as-is out of the box so I just added a User serializer:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['id', 'username']
A Viewset:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
And added to urls:
router.register(r'users', UserViewSet)
From DRF Docs:
drf docs note source
Note: If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as view_name='app_name:user-detail' for serializer fields hyperlinked to the user detail view.
The automatic view_name generation uses a pattern like %(model_name)-detail. Unless your models names actually clash you may be better off not namespacing your Django REST Framework views when using hyperlinked serializers.
Solution
example of setting view_name
from rest_framework import serializers
from myapp.models import Post
from django.contrib.auth.models import User
class PostSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:post-detail")
author = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True)
viewers = serializers.HyperlinkedRelatedField(view_name="api:user-detail", read_only=True, many=True)
class Meta:
model = Post
fields = ('id', 'title', 'url', 'author', 'viewers')
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"

Django adminsite customize search_fields query

In the django admin you can set the search_fields for the ModelAdmin to be able to search over the properties given there. My model class has a property that is not a real model property, means it is not within the database table. The property relates to another database table that is not tied to the current model through relations.
But I want to be able to search over it, so I have to somehow customize the query the admin site creates to do the filtering when the search field was filled - is this possible and if, how?
I can query the database table of my custom property and it then returns the ids of the model classes fitting the search. This then, as I said, has to flow into the admin site search query.
Thanks!
Since django 1.6, you can customize the search by defining a get_search_results method in your ModelAdmin subclass.
It is well explained in django documentation. The following example is copied from this doc.
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'age')
search_fields = ('name',)
def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
try:
search_term_as_int = int(search_term)
queryset |= self.model.objects.filter(age=search_term_as_int)
except:
pass
return queryset, use_distinct
You should use search_fields = ['foreign_key__related_fieldname']
like search_fields = ['user__email'] in the admin class that extends admin.ModelAdmin
read more here
this might can help
search_fields = ['foreign_key__related_fieldname']
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields

Categories