Django Rest Api - сделать запрос с массивом в ManyToManyField - PullRequest
0 голосов
/ 28 мая 2019

Django Rest Api - отправить запрос с массивом в ManyToManyField.

Я хочу отправить запрос через почтальона, отправив, таким образом, название, описание и массив упражнений [{'Bicep Curl'}, {Tricep Pushdown}, {Cable Flies}].

Это мои модели:

class Bodypart(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
    return self.name

class Exercise(models.Model):
name = models.CharField(max_length=40)
bodyparts = models.ManyToManyField(Bodypart, blank=True)

def __str__(self):
    return self.name

class Cardio(models.Model):
name = models.CharField(max_length=40)
time = models.IntegerField(default=10)

def __str__(self):
    return self.name

class Meta:
    verbose_name_plural = 'cardio'

class Workout(models.Model):
title = models.CharField(max_length=120)
description = models.CharField(max_length=1000, blank=True)
exercises = models.ManyToManyField(Exercise, blank=True)
cardio = models.ManyToManyField(Cardio, blank=True)

def __str__(self):
    return self.title

Это мои сериализаторы:

class BodypartSerializer(serializers.ModelSerializer):
class Meta:
    model = Bodypart
    fields = ('id', 'name')

class ExerciseSerializer(serializers.ModelSerializer):
class Meta:
    model = Exercise
    fields = ('id', 'name', 'bodyparts')

class ExerciseSerializerName(serializers.ModelSerializer):
class Meta:
    model = Exercise
    fields = ('name', )

class CardioSerializer(serializers.ModelSerializer):
class Meta:
    model = Cardio
    fields = ('id', 'name', 'time')

class CardioSerializerName(serializers.ModelSerializer):
class Meta:
    model = Cardio
    fields = ('name', 'time', )

class WorkoutSerializer(serializers.ModelSerializer):
exercises = ExerciseSerializerName(many=True, read_only=True)
cardio = CardioSerializerName(many=True, read_only=True)
class Meta:
    model = Workout
    fields = ('id', 'title', 'description', 'exercises', 'cardio')

Мои URL:

router = routers.DefaultRouter()
router.register('workouts', views.WorkoutView)
router.register('exercises', views.ExerciseView)
router.register('cardio', views.CardioView)
router.register('bodyparts', views.BodypartView)

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

Мои просмотры:

class WorkoutView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Workout.objects.all()
serializer_class = WorkoutSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

class ExerciseView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Exercise.objects.all()
serializer_class = ExerciseSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

class CardioView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Cardio.objects.all()
serializer_class = CardioSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

class ExerciseViewName(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Exercise.objects.all()
serializer_class = ExerciseSerializerName

class BodypartView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Bodypart.objects.all()
serializer_class = BodypartSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

My Rest Api построен так:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
"workouts": "http://localhost:8000/database/workouts/",
"exercises": "http://localhost:8000/database/exercises/",
"cardio": "http://localhost:8000/database/cardio/",
"bodyparts": "http://localhost:8000/database/bodyparts/"
}

Разминка:

HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        {
            "name": "Tricep Cable Pushdown"
        },
        {
            "name": "Delt Side Raises"
        },
        {
            "name": "Delt Barbell Press"
        },
        {
            "name": "Chest Cable Flyes"
        },
        {
            "name": "Barbell Bench Press"
        }
    ],
    "cardio": [
        {
            "name": "Stairmaster",
            "time": 12
        }
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        {
            "name": "Bicep Cable Curl"
        },
        {
            "name": "Back Barbell Row"
        },
        {
            "name": "Back Pullback Machine"
        }
    ],
    "cardio": [
        {
            "name": "Bike",
            "time": 10
        }
    ]
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": []
}
]

Как вы можете видеть на тренировках. Что я хочу сделать - это отправить запрос на публикацию, выбрав несколько полей из упражнения api.

...