I have the following models.
class ServerGroup(models.Model):
name = models.SlugField(unique=True)
factor = models.IntegerField()
class ServerGroupMember(models.Model):
class Meta:
unique_together = (
("server_group", "position"),
("server_group", "server"),
)
position = models.IntegerField()
server_group = models.ForeignKey(
"ServerGroup", related_name="servers", on_delete=models.CASCADE
)
server = models.ForeignKey("Server", on_delete=models.CASCADE)
A ServerGroup has a couple of properties, name
and factor
, and a collection of ServerGroupMember
objects. Each ServerGroupMember
object, contains an integer position
and a reference to a Server
object. For a given ServerGroup
the position
must be unique, and for a given ServerGroup
the server
must be unique. However, globally, the position and server objects do not have to be unique, as in 2 ServerGroups may contain a server at postion 1, and the same Server may appear in multiple Server Groups, just not multiple times in the same Server Group.
Given that I have the following serializers, how can I validate the above? The model currently does validate the condition at the database level, but will raise a unique constraint error if I attempt to violate it. What I want is to be able to detect this in my views, such that I can return an appropriate validation error message response before it has a chance to hit the DB and raise that exception.
class ServerGroupMemberSerializer(serializers.ModelSerializer):
class Meta:
model = models.ServerGroupMember
fields = ("position", "server")
server = serializers.SlugRelatedField(
slug_name="name", queryset=models.Server.objects.all()
)
class SrvereGroupSerializer(serializers.ModelSerializer):
class Meta:
model = models.ServerrGroup
fields = ("name", "factor", "servers")
servers = ServerGroupMemberSerializer(many=True, required=False)
def create(self, validated_data): ...
def update(self, validated_data): ...