0

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

Community
  • 1
  • 1
Clocker
  • 1,316
  • 2
  • 19
  • 29

1 Answers1

0

Sorry, was already answered: Django Unique Together (with foreign keys)

What you are looking for might be already provided by the many to many relation. Can you use that relation on user or room instead ?

Community
  • 1
  • 1
Roba
  • 646
  • 4
  • 13
  • I think I could. I ended up overwriting the perfrom_create(self, serializer) on my view instead. Executed to filters on it and check if it exists. I do wonder the performance of that method as the DB gets large. – Clocker Oct 12 '15 at 17:20
  • There will be a performance impact but I would say it's negligible - it happens only at object creation. Another way to approach this is to write a custom object manager where you overwrite the create method. This way you are hardening the condition as close to the dB layer as possible, making such a validation available for admin site as well. – Roba Oct 13 '15 at 02:25