【问题标题】:Query for favorites of user in Django在 Django 中查询用户的收藏夹
【发布时间】:2021-11-10 11:56:07
【问题描述】:

我想查询用户在 Django 中的收藏夹。每个用户都有一个配置文件(userprofile),收藏夹存储在这个 userprofile 模型中。我希望能够仅使用用户的 id 来查询收藏夹(它们是用户配置文件)。这是我所拥有但不起作用的(即使用户有 3 个收藏夹,它也会返回一个空查询):

favorites = UserProfile.objects.filter(favorites__user__id=user_id)

我的用户模型:

class User(AbstractUser):
  usertype = models.PositiveSmallIntegerField(choices=constants.USER_TYPE_CHOICES )
  profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=False)
  token = models.CharField(max_length=10, default='')

我的用户档案模型:

class UserProfile(models.Model):
  birth_date = models.DateField(default=datetime.date(1900, 1, 1))
  favorites = models.ManyToManyField('self', symmetrical=False)

我应该怎么做? 非常感谢!

【问题讨论】:

    标签: python django sqlite django-models


    【解决方案1】:
    favorites = User.objects.get(id=user_id).profile.favorites.all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2021-05-28
      • 1970-01-01
      相关资源
      最近更新 更多