Search code examples
djangounique-constraint

how to call back unique together constraints as a field django


i'm trying to call back unique constraints field , in my project i have to count number of M2M selected

class Booking(models.Model):
    room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms')
    takes_by = models.ManyToManyField(Vistor)

    @property
    def no_persons(self):
        qnt =  Booking.objects.filter(takes_by__full_information=self).count()#but this doesnt  work
        return qnt

Cannot query "some room information": Must be "Vistor" instance.

class Vistor(models.Model):
    full_name = models.CharField(max_length=150)
    dob = models.DateField(max_length=14)
    city = models.ForeignKey(City,on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information')
        ]

    def __str__(self):
        return f'{self.full_name} - {self.city} - {self.dob}'

it it possible to access full_information through Booking model ? thank you ..


Solution

  • If you want to count the number of Visitors related to that booking, you can count these with:

    @property
    def no_persons(self):
        self.taken_by.count()

    This will make an extra query to the database, therefore it is often better to let the database count these in the query. You can thus remove the property, and query with:

    from django.db.models import Count
    
    Booking.objects.annotate(
        no_persons=Count('takes_by')
    )

    The Bookings that arise from this QuerySet will have an extra attribute no_persons with the number of related Visitors.