Как перенести заказ по умолчанию в Django
У меня есть две модели, Exercise и Workout. Когда я добавляю список упражнений в таблицу Workout, они добавляются в алфавитном порядке. Я не хочу этого. Я использую ajax для отправки списка exercise_id в нужном мне порядке, затем в своем views.py я получаю упражнения по id и добавляю их в таблицу workout. Я хочу сохранить порядок добавления упражнений. Как мне это сделать? Ниже приведены фрагменты моего кода.
BODYPART_CHOICES = (
('Abs', 'Abs'), ('Ankle', 'Ankle'),
('Back', 'Back'), ('Biceps', 'Biceps'),
('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'),
('Forearms', 'Forearms'), ('Full Body', 'Full Body'),
('Hip', 'Hip'),
('Knee', 'Knee'),
('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'),
('Neck', 'Neck'),
('Shoulders', 'Shoulders'),
('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'),
('Wrist', 'Wrist'),
)
CATEGORY_CHOICES = (
('Cardio', 'Cardio'),
('Stability', 'Stability'),
('Flexibility', 'Flexibility'),
('Hotel', 'Hotel'),
('Pilates', 'Pilates'), ('Power', 'Power'),
('Strength', 'Strength'),
('Yoga', 'Yoga'),
('Goals & More', 'Goals & More'),
('Activities', 'Activities'),
('Rehabilitation', 'Rehabilitation'),
('Myofascial', 'Myofascial')
)
EQUIPMENT_CHOICES = (
('Airex', 'Airex'),
('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'BattleRope'), ('Bodyweight', 'Bodyweight'),('Bands', 'Bands'),
('Cables', 'Cables'), ('Cones', 'Cones'),
('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'),
('Foam Roller', 'Foam Roller'),
('Kettlebells', 'Kettlebells'),
('Leg Weights', 'Leg Weights'),
('Machine', 'Machine'), ('Medicine Ball', 'Medicine Ball'),
('Plate', 'Plate'), ('Power Wheel', 'Power Wheel'),
('Ring', 'Ring'),
('Sandbag', 'Sandbag'), ('Stick', 'Stick'), ('Strap', 'Strap'), ('Suspension', 'Suspension'), ('Swiss Ball', 'Swiss Ball'),
('Theraball', 'Theraball'), ('Towel', 'Towel'), ('Tubbing', 'Tubbing'),
('Wobble Board', 'Wobble Board'),
)
name = models.CharField(max_length=200)
photograph = models.ImageField(null=True, upload_to=exercise_image_file_path)
body_part = models.CharField(max_length=50, choices=BODYPART_CHOICES)
equipment = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES)
equipment_two = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES, blank=True, null=True)
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES)
workout_tip = models.TextField(max_length=3000, blank=True)
cmf_url = models.URLField(max_length=400, blank=True)
def __str__(self):
return self.name
и
class Workout(models.Model):
GOALS_CHOICES = (
('None', 'None'),
('Abs', 'Abs'), ('Arms', 'Arms'),
('Cardio', 'Cardio'), ('Core', 'Core'),
('Endurance', 'Endurance'),
('Flexibility', 'Flexibility'), ('Full Body', 'Full Body'),
('Legs', 'Legs'), ('Lower Body', 'Lower Body'),
('Power', 'Power'),
('Shoulders', 'Shoulders'), ('Sport Conditioning', 'Sport Conditioning'), ('Stability', 'Stability'), ('Strength', 'Strength'),
('Toning', 'Toning'),
('Upper Body', 'Upper Body'),
('Weight Loss', 'Weight Loss')
)
name = models.CharField(max_length=200, blank=True)
exercises = models.ManyToManyField(Exercise)
profile = models.ForeignKey(Profile, on_delete=SET_NULL,null=True, blank=True)
description = models.TextField(max_length=3000, blank=True)
goals = models.CharField(max_length=25, choices=GOALS_CHOICES, default='None')
workout_time = models.CharField(max_length=200, blank=True)
difficulty = models.CharField(max_length=200,blank=True)
def __str__(self):
return self.name
$.ajax({
type: 'POST',
url: workoutURL,
enctype: 'multipart/form-data',
datatype: 'json',
data:{
csrfmiddlewaretoken: csrftoken,
exercises: exercises
},
success: (response)=>{
console.log(response)
},
error: (error)=>{
console.log(error)
}
})
views.py
def workout_builder(request):
form = ExerciseFilterForm()
data = {}
if request.method == 'POST' and request.is_ajax():
exercises = request.POST.getlist('exercises[]')
workout = Workout(
name="Temp"
)
workout.save()
for ex in exercises:
exercises = Exercise.objects.get(id=ex)
workout.exercises.add(exercises)
data['status'] = 'ok'
data['workout_id'] = workout.id
return JsonResponse(data)
return redirect(workout_detail, pk=workout.pk)
return render(request, 'workouts/workout_exercise.html', {'form': form})
В вашей модели Workout
попробуйте добавить
class Workout(models.Model):
# your code
class Meta:
ordering = ['-id']