2

i have two models Stats and Autor, how i can change primary key to use a unqiue field search by parameter(Subname in Autor model) i thinking about APIView but anyone can show me how use this? example : http://127.0.0.1:8000/autors/Subname

models.py

class Stats(models.Model):

# Fields
Word = models.CharField(name='Word',max_length=255)
Word_count = models.IntegerField(name="Count")

def __str__(self):
    return self.Word+":"+str(self.Count)

class Autor(models.Model):

name = models.CharField(max_length=255)
sub_name = models.CharField(name='Subname', max_length=255, default='puste')
# Relationship Fields
words = models.ManyToManyField(Stats)

serializers.py

class StatsSerializer(serializers.ModelSerializer):
class Meta:
    model=Stats
    fields=('Word','Count')

class AutorSerializer(serializers.ModelSerializer):
words=StatsSerializer(read_only=True,many=True)
class Meta:
    model=Autor
    fields=('name','words')

Views.py

class AutorView(viewsets.ModelViewSet):
queryset = Autor.objects.all()
serializer_class = AutorSerializer

class StatsView(viewsets.ModelViewSet):
    serializer_class = StatsSerializer
    queryset = Stats.objects.all()

Urls.py

from django.contrib import admin
from django.urls import path,include
from Teonite import views
from rest_framework import routers

router=routers.DefaultRouter()
router.register('autors',views.AutorView)

urlpatterns = [
    path('',include(router.urls))
]

I using django 2.0, python 3.6 and Django REST framework 3.8.2

kowal666
  • 61
  • 8

1 Answers1

4

First of all, make sub_name field to unique as,

class Autor(models.Model):
    name = models.CharField(max_length=255)
    sub_name = models.CharField(name='Subname', max_length=255, default='puste',unique=True)
    # Relationship Fields
    words = models.ManyToManyField(Stats)


Then, change lookup-field attribute in your view as,

class AutorView(viewsets.ModelViewSet):
    queryset = Autor.objects.all()
    serializer_class = AutorSerializer
    lookup_field = sub_name


If you didn't change to unique field in models, it may cause error, because the Detail API retrives only One instance with respect to the lookup-field

JPG
  • 82,442
  • 19
  • 127
  • 206