简体   繁体   English

如何在 Django 中查询多对多字段

[英]How to query many-to-many field in Django

I'm trying to update a view I have that returns all my items from my pets table given the current logged in user.我正在尝试更新我拥有的视图,该视图根据当前登录的用户从我的 pets 表中返回我的所有项目。 I have in Pet a many-to-many field petowners .我在Pet有一个多对多领域的petowners

The PetOwner model is as follows... PetOwner模型如下...

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... Pet模型如下...

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).我正在使用 Django 已经提供给我们的User进行身份验证(注册和登录)。 A PetOwner is created when a user creates their account, alongside with their first and last name.当用户创建他们的帐户时,会创建一个PetOwner ,以及他们的名字和姓氏。 The PetOwner has only the email , phone_number , and address as unique fields but not required. PetOwner只有emailphone_numberaddress作为唯一字段,但不是必需的。 Therefore, the guaranteed of uniqueness is from the username from Django's User model.因此,唯一性的保证来自 Django 的User模型的User username

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.我不知道如何编写此查询。

First set the related_name of owners field:首先设置owners字段的related_name

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM