简体   繁体   中英

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

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.

You can query with:

Beerpost.objects.exclude()

with user the user object for which you want to obtain Beerpost objects where user is not part of the ratings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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