我有两种模式:
class Album(models.Model):
name = models.CharField()
class Track(models.Model):
album = models.ForeignKey(Album)
name = models.CharField()
我无法理解如何创建一个Track实例,使用POST端点/曲目,传递专辑ID而不是专辑对象,但保留专辑对象的GET请求。
答案 0 :(得分:0)
您需要为您的班级创建Serializer并执行此操作:
def post(self, request, albumId, format=None):
try:
album = Album.objects.get(pk=albumId)
except Sensor.DoesNotExist:
raise Http404
serializer = TrackSerializer(data=request.data)
if serializer.is_valid():
serializer.validated_data["album_id"] = album.id
measurement = serializer.save()
允许Track.album为null的序列化程序:
class TrackSerializer(serializers.HyperlinkedModelSerializer):
album= PrimaryKeyRelatedField(queryset=Album.objects.all(), required=False)
class Meta:
model = Track
fields = ('id', 'name;)
并且网址:
url(r'^albums/(?P<albumId>[0-9]+)/$', views.AlbumView.as_view(), name='albums'),
您将一个Track对象发布到yourURL / {albumId},以将其添加到ID = albumId
的相册中