Home > Software design >  How to query many-to-many field in Django
How to query many-to-many field in Django

Time:11-10

I'm trying to update a view I have that returns all my items from my pets table given the current logged in user. I have in Pet a many-to-many field petowners.

The PetOwner model is as follows...

class PetOwner(models.Model):
    """Model representing a pet owner."""

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50, help_text="Enter owner's first name")
    last_name = models.CharField(max_length=50, help_text="Enter owner's last name")
    email = models.EmailField(
        max_length=50, blank=True, null=True, unique=True, help_text="Enter owner's email"
    )
    phone_number = models.CharField(
        max_length=15, blank=True, null=True, unique=True, help_text="Enter owner's phone number"
    )
    address = models.ForeignKey(
        "Address", on_delete=models.SET_NULL, null=True, blank=True
    )

The Pet model is as follows...

class Pet(models.Model):
    """Model representing a pet."""

    first_name = models.CharField(max_length=50, help_text="Enter pet's first name")
    last_name = models.CharField(max_length=50, help_text="Enter pet's last name")
    breeds = models.ManyToManyField("Breed", help_text="Select a breed for this pet")
    weight = models.DecimalField(
        max_digits=5, decimal_places=2, help_text="Enter pet's weight"
    )
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField("Died", null=True, blank=True)
    owners = models.ManyToManyField(PetOwner, help_text="Select an owner for this pet")
    address = models.ForeignKey(
        "Address", on_delete=models.SET_NULL, null=True, blank=True
    )

I am using the User that is already given to us by Django for authentication (registering and login). A PetOwner is created when a user creates their account, alongside with their first and last name. The PetOwner has only the email, phone_number, and address as unique fields but not required. Therefore, the guaranteed of uniqueness is from the username from Django's User model.

I do not want to return all of the pets in my database instead I want to return only the pets for the current user that is logged in. Something like the following...

Pet.objects.filter(owners.contain(request.user))

Maybe by using the username? I don't know how to write this query.

CodePudding user response:

First set the related_name of owners field:

class Pet(models.Model):
    """Model representing a pet."""

    first_name = models.CharField(max_length=50, help_text="Enter pet's first name")
    last_name = models.CharField(max_length=50, help_text="Enter pet's last name")
    breeds = models.ManyToManyField("Breed", help_text="Select a breed for this pet")
    weight = models.DecimalField(
        max_digits=5, decimal_places=2, help_text="Enter pet's weight"
    )
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField("Died", null=True, blank=True)
    owners = models.ManyToManyField(PetOwner, help_text="Select an owner for this pet", related_name='pets')  # <- Here
    address = models.ForeignKey(
        "Address", on_delete=models.SET_NULL, null=True, blank=True
    )

Then you can make this query to get the pets of an user:

target_user = User.objects.get(id=1)  # This is only an example
pet_owner = PetOwner.objects.get(user=target_user)
pets = pet_owner.pets.all()
  • Related