This question seems to be similar to what I am aiming for but I get an error
IntegrityError column username_id is not unique
What I am looking for is having these fields be unique only when together. Meaning that the same roomId
and username can only be seen in the database once when together.
However, a user can be seen with another roomId
. The point is to avoid multiple submissions of the same user and the same roomId
.
The error above occurs when I try to submit another requst with the same username to another roomId
.
Here is my model
class Active(models.Model):
username = models.ForeignKey(Profile)
roomId = models.ForeignKey(Room)
activeId = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)
class Meta:
unique_together=(('username', 'roomId',))
I am using SQLite
and.
I thought the unique_together constraint did this but it doesn't seem like it. What's the proper approach?
Edit
I ended up overriding the perform_create and verify that no row contains both keys before saving like in this link.
def perform_create(self, serializer):
queryset = Active.objects.filter(username=serializer.data.get('username')).filter(roomId=serializer.data.get('roomId'))
if queryset.exists():
raise ValidationError({"detail" : "dont be silly"})
serializer.save()
Seems to be working fine.
Regards