Как реализовать сложную логику валидации для моделей?

Я пытаюсь реализовать простой REST API для приложения геокешинга.

  1. each geocache has several stations
  2. once a geocache instance is created you should be able to append stations
  3. the stations of a geocache have a fixed order (implemented through position)
  4. if a new station gets inserted at a specific position, all subsequent stations should be shifted
  5. an operation like 4. should set the geocache flag released to False (not released geocaches should not be shown to the user)
  6. 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()

Есть два случая, которые мне нужно проверить:

  1. Is the position of the new station in the range from 1 to ([highest position] + 1)?
  2. When a geocache gets updated and released = True, is there at least one station for that geocache?

У меня возникают проблемы с тем, куда поместить эти проверки валидности. Я знаю о трех потенциальных возможностях:

  1. Model-level validation (through clean-methods) what is no longer natively supported in DRF 3
  2. 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.)
  3. 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 и буду благодарен за любую помощь. Тем не менее, во время своих исследований я столкнулся с людьми, отстаивающими все эти три способа.

Вернуться на верх