2

我有两个模型 Stats 和 Autor,我如何更改主键以通过参数(Autor 模型中的子名)使用 unqiue 字段搜索我正在考虑 APIView,但任何人都可以告诉我如何使用它?示例: http: //127.0.0.1 :8000/autors/Subname

模型.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)

序列化程序.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')

视图.py

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

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

网址.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))
]

我使用 django 2.0、python 3.6 和 Django REST framework 3.8.2

4

1 回答 1

4

首先,将sub_name字段设为uniqueas,

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)


然后,将视图中的查找字段属性更改为,

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


如果您没有更改模型中的唯一字段,则可能会导致错误,因为Detail API仅检索One相对于lookup-field

于 2018-07-25T03:48:47.037 回答