13👍
✅
This is how I managed to hack it
models.py
from django.db import models
from django.contrib.auth.models import User
class Speaker(models.Model):
user = models.OneToOneField(User)
@property
def user__username(self):
return self.user.username
def __unicode__(self):
return self.user.username
serializers.py
from .models import Speaker
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
lookup_field = 'username'
class SpeakerSerializer(serializers.HyperlinkedModelSerializer):
user = serializers.HyperlinkedRelatedField(
view_name='user-detail',
read_only=True,
lookup_field='username'
)
class Meta:
model = Speaker
fields = ('url', 'user')
lookup_field = 'user__username'
view.py
from .models import Speaker
from .serializers import SpeakerSerializer, UserSerializer
from rest_framework import viewsets
from django.contrib.auth.models import User
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'username'
class SpeakerViewSet(viewsets.ModelViewSet):
queryset = Speaker.objects.all().select_related('user')
serializer_class = SpeakerSerializer
lookup_field = 'user__username'
1👍
The only thing I changed from your code is to override the get_object
method by filtering with the username instead of the default pk
. I also changed the lookup_field
to a descriptive name and used ModelSerializer
and StringRelated
in the serializer.py
.
models.py
class Speaker(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
serializer.py
class SpeakerSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(read_only=True)
class Meta:
model = Speaker
lookup_field = "username"
fields = "__all__"
views.py
class SpeakerViewSet(ModelViewSet):
queryset = Speaker.objects.all().select_related("user")
serializer_class = SpeakerSerializer
lookup_field = "username"
def get_object(self):
"""Return the object for this view."""
return get_object_or_404(self.queryset, user__username=self.kwargs["username"])
urlconf
api/ ^speaker/$ [name='speaker-list']
api/ ^speaker\.(?P<format>[a-z0-9]+)/?$ [name='speaker-list']
api/ ^speaker/(?P<username>[^/.]+)/$ [name='speaker-detail']
api/ ^speaker/(?P<username>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='speaker-detail']
- [Django]-Switching to PostgreSQL fails loading datadump
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-Get count of related model efficiently in Django
0👍
Have you tried this approach?
class SpeakerViewSet(viewsets.ModelViewSet):
queryset = Speaker.objects.all().select_related('user')
serializer_class = SpeakerSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('user', 'user__username',)
- [Django]-Django Admin app or roll my own?
- [Django]-Get object by field other than primary key
- [Django]-CORS error while consuming calling REST API with React
0👍
I’m fetching user’s settings with user’s ID [GET / Update]
urls.py
path('user/<int:user_id>/settings/preferences/', UserPreferenceSettingsView.as_view(), name="settings_preferences")
models.py
class UserSetting(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
adult_lock = models.BooleanField(default=False)
child_lock = models.BooleanField(default=False)
promotional_email = models.BooleanField(default=True)
update_email = models.BooleanField(default=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
class UserPreferenceSettingsView(generics.RetrieveUpdateAPIView):
http_method_names = ['get', 'patch']
serializer_class = UserPreferenceSettingsSerializer
def get_object(self):
lookup_field = self.kwargs["user_id"]
return get_object_or_404(UserSetting, user__pk=lookup_field)
If you need to fetch from username
just replace user_id to username
and url <int:user_id>
to <username> or <str:username>
- [Django]-Naming convention for Django URL, templates, models and views
- [Django]-Django 1.7 – App 'your_app_name' does not have migrations
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
Source:stackexchange.com