Cannot call QuerySet with a ForeignKey in Django

Viewed 60

Version

Mac OS : 10.15.6 Django : 3.7.6

What I want to do

Get all Want_Items that are had by a specific user

Hello, I'm a beginner to Django. I am trying to create an app that each can exchange their items. I created models, User, Parent_Item, Want_Item, Give_Item. And I set relations between them like below.

  • User - Parent_Item => One To Many
  • Parent_Item - Give_Item => One To Many
  • Parent_Item - Want_Item => One To Many

I succeeded in getting all parent_item that one user has. However, I cannot get want_item for some reason. This is my attempts and errors I was faced with.

>>>toshi_want = Toshi.item.want_item.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'RelatedManager' object has no attribute 'want_item'

>>> toshi_all=Toshi.item.all()
>>> print(toshi_all)
<QuerySet [<Parent_Item: MacBook>, <Parent_Item: Desk>, <Parent_Item: shirt>]>
>>> print(toshi_all.want_item.all())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'want_item'

I surely set a ForeignKey with related_name = "want_item". Why cannot I use this in this case??

I would like you to teach me solutions and why it happens.

models.py

class User(models.Model):
    username = models.CharField(max_length=150, unique=True)
    email = models.EmailField(max_length=100, unique=True)
    password = models.CharField(max_length=20)
    confirm_pass = models.CharField(max_length=20)
    profile = models.TextField(max_length=800, blank=True, null=True)
    icon = models.ImageField(blank = True, null = True)
    login = models.BooleanField(default=False)
    # createdAt, updatedAt は時系列順等に並べたいモデルに付与
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.username

    class Meta:
        db_table = "users"



class Give_Item(models.Model):
    ITEM_STATE = (
        ("新品", "新品、未使用"),
        ("未使用", "未使用に近い"),
        ("傷や汚れなし", "目立った傷や汚れなし"),
        ("やや傷や汚れあり", "やや傷や汚れあり"),
        ("傷や汚れあり", "傷や汚れあり"),
        ("状態が悪い", "全体的に状態が悪い")
    )
    state = models.CharField(max_length=20, choices=ITEM_STATE, default="新品")
    detail = models.TextField(max_length=800, blank=True, null=True)
    category = models.ForeignKey("Category", related_name="give_item", on_delete = models.SET_NULL, null = True)
    parent_item = models.ForeignKey("Parent_Item", null=True, on_delete=models.CASCADE, related_name="give_item")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.parent_item.name

    class Meta:
        db_table = "give_items"

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class Want_Item(models.Model):
    url = models.URLField(max_length=250, null=True, blank=True)
    parent_item = models.ForeignKey("Parent_Item", null=True, on_delete=models.CASCADE, related_name="want_item")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.parent_item.name

    class Meta:
        db_table = "want_items"

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

class Parent_Item(models.Model):
    name = models.CharField(max_length=100)
    owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="item")
    # テーブル内のフィールドはRequst, Deal の外部キー(requet, deal)
    keyword = models.ManyToManyField(Keyword, related_name = "parent_item")
    # Blandは一つしか選べないため、OneToMany関係
    bland = models.ForeignKey(Bland, related_name="parent_item", on_delete=models.SET_NULL, null=True)
    request_deal = models.ForeignKey("Request_Deal", null=True, on_delete=models.CASCADE, related_name="parent_item")
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "parent_items"

2 Answers

Something like this?

user_primary_key = 1
Want_Item.objects.filter(parent_item__owner=user_primary_key)

i cant comment so i gonna answer you here . your model "want_item" has relation with "parent_item" with related name "want_item" not your User model! you can use: User.item.want_item

Related