[Answered ]-Join Queries in Django

0👍

reservation = Reservation.objects.select_related(‘personel_id’).filter(id=pk, personel_id__id=current_user)

Its done!

1👍

You can fetch the Reservation with id=3 and where the personel_id_id is 2 with:

Reservation.objects.get(
    id=3,
    personel_id_id=2
)

but ForeignKeys normally have no …_id suffix: Django will automatically add an …_id suffix for the field that stores the id of the user. You thus should implement your model as:

from django.conf import settings

class Reservation(models.Model):
    personel = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    reservation_title = models.CharField(max_length=30)
    reservation_situation = models.BooleanField(default=False)

and thus filter with:

reservation = Reservation.objects.get(
    id=3,
    personel_id=2
)

you can access the details of the user with reservation.personel, which is then a user model object.

If you want to fetch the user details in the same query, which thus saves an extra roundtrip to the database, you can use:

reservation = Reservation.objects.select_related('personel').get(
    id=3,
    personel_id=2
)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment