python - 如何在 Django orm 中链接和过滤 3 个表中的数据

标签 python django orm

我想过滤用户尚未投票的帖子(啤酒)。为此,我需要将帖子与评级表和有用户的帮助表结合起来。 数据库中的示例表评级 https://drive.google.com/file/d/1MkL4IVtviIcPo7XFptoybPthNyO4dUp_/view?usp=sharing 我的模特帖子

class Beerpost(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, editable=False)
    title = models.CharField("Назва", max_length=160)
    slug = models.SlugField(max_length=160, unique=True)
    img = ProcessedImageField(upload_to='static/img/%Y/%m/%d/%H/%M/%S/', processors = [ResizeToFit(150, 385)], format='JPEG', options={'quality': 90})    
    type_beer = models.ForeignKey(
        Type,
        verbose_name="Тип пива",
        on_delete=models.SET_NULL,
        null=True,
        blank=True, default=1)
    volume = models.ForeignKey(Vol, verbose_name="Об'єм л.", on_delete=models.CASCADE, null=True, blank=True, default=3)
    price_limit = models.ForeignKey(Price, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Орієнтовна ціна', default=4)   
    country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Країна', default=3)
    created = models.DateTimeField("Дата створення", auto_now_add=True)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    ratings = GenericRelation(Rating, related_query_name='foos')
    favorite = models.BooleanField(default=False, editable=False)
    users_reaction_favorite = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users_reaction_favorite", editable=False)

我试试这个

all_beer = Beerpost.objects.all()
user_table = UserRating.objects.filter(user_id = pk)
join_user_table = user_table.select_related()

但我不知道如何组合这 3 个查询。请帮助我,我三天无法解决这个问题(请帮助我,我三天无法解决这个问题(或推荐我一些其他解决方案。

最佳答案

您可以通过以下方式查询:

Beerpost.objects.exclude(<b>ratings__user=<i>user</i></b>)

user 是您想要为其获取 Beerpost 对象的用户对象,其中 user不是评级的一部分。

关于python - 如何在 Django orm 中链接和过滤 3 个表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57691192/

相关文章:

python - 帮助在 Django、Zope3 和 Web2Py 之间为 WebService Server 选择

python - 使用模板中的表单访问模型字段的属性

python - 如何按 3 列打印 2 本词典

python - 在文件中查找字符串的最快方法

python - 运行时错误 : The init_func must return a sequence of Artist objects

EC2 ubuntu 静态文件问题上的 Django 应用程序

java - hibernate 保存/更新级联

java - Hibernate 映射异常

javascript - 如何使用sequelize和mysql创建一对一关系?

python - 模块未找到错误 : No Module Named openai