简体   繁体   English

如何从Django Orm中的3个表链接和过滤数据

[英]How to link and filter data from 3 tables in Django orm

I want to filter posts (beer) for which the user has not yet voted. 我想过滤用户尚未投票的帖子(啤酒)。 To do this, I need to combine posts with a rating table and a help table where there is a user. 为此,我需要将帖子与评分表和有用户的帮助表结合起来。 Example tables raiting in db https://drive.google.com/file/d/1MkL4IVtviIcPo7XFptoybPthNyO4dUp_/view?usp=sharing My model post 在db 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)

I try this 我尝试这个

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

But I don't know how combine this 3 queries. 但是我不知道如何结合这三个查询。 Pleace help me, I three days can't solve this problem( Please help me, I three days can't solve this problem( or recommend me some others solution. 请Pleace帮我,我三天不能解决这个问题(请帮助我,我三天不能解决这个问题(或向我推荐其他解决方案。

You can query with: 您可以使用以下查询:

Beerpost.objects.exclude(ratings__user=user)

with user the user object for which you want to obtain Beerpost objects where user is not part of the ratings . user的用户对象,您要为其获得Beerpost对象,而user 属于ratings

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

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