Как реализовать сложную логику валидации для моделей?
Я пытаюсь реализовать простой REST API для приложения геокешинга.
- each geocache has several stations
- once a geocache instance is created you should be able to append stations
- the stations of a geocache have a fixed order (implemented through
position
) - if a new station gets inserted at a specific position, all subsequent stations should be shifted
- an operation like 4. should set the geocache flag
released
toFalse
(not released geocaches should not be shown to the user) - a geocache can only be released if there exists at least one station
Если у вас есть следующая модель.
models.py
class Geocache(models.Model):
title = models.CharField(max_length=70)
released = models.BooleanField(default=False)
class Station(models.Model):
class Meta:
unique_together = (('geocache', 'position'),)
ordering = ['geocache', 'position']
geocache = models.ForeignKey(Geocache, related_name='stations', on_delete=models.CASCADE)
position = models.IntegerField()
title = models.CharField(max_length=70)
instruction = models.TextField()
Есть два случая, которые мне нужно проверить:
- Is the position of the new station in the range from
1
to([highest position] + 1)
? - When a geocache gets updated and
released = True
, is there at least one station for that geocache?
У меня возникают проблемы с тем, куда поместить эти проверки валидности. Я знаю о трех потенциальных возможностях:
- Model-level validation (through
clean
-methods) what is no longer natively supported in DRF 3 - Serializer-level validation (through field- and object-validation methods) which only seems to enable local validation and does not consider the integrity of object relations (what i need for 2.)
- View level validation which seems to be too far away from the model and does not assure data integrity when the model is accessed from elsewhere
Я совсем новичок в DRF и Django и буду благодарен за любую помощь. Тем не менее, во время своих исследований я столкнулся с людьми, отстаивающими все эти три способа.