Home > OS >  Django: How to get value from foreign key and next foreign key?
Django: How to get value from foreign key and next foreign key?

Time:05-30

We need to get cost from Reward, but we must use TwitchUser

it`s my models.py

class TwitchUser(models.Model):
    username = models.CharField(max_length=250, verbose_name='username', null=True)
    refresh_token = models.CharField(max_length=300, verbose_name='refresh_token', null=True)
    id = models.CharField(max_length=150 ,primary_key=True)
    login = models.CharField(max_length=250, null=True)
    avatar = models.CharField(max_length=400, verbose_name='avatar')
    params = models.ForeignKey('Parametrs', on_delete=models.CASCADE)

class Parametrs(models.Model):
    skip = models.ForeignKey('Reward', on_delete=CASCADE)
    chat_bot = models.BooleanField(default=False)

class Reward(models.Model):
    id = models.CharField(primary_key=True, max_length=50)
    title = models.CharField(null=True, max_length=50)
    cost = models.IntegerField(default=0)
    background_color = models.CharField(max_length=30, verbose_name='color', default='FFD600')
    cooldown = models.IntegerField(default=30)
    type = models.CharField(max_length=100, )

CodePudding user response:

If you want to get rewards by Parametrs and TwitchUser ids, you can use:

Reward.objects.filter(parametrs__pk=<parametr_id>, parametrs__twitchuser__pk=<twitch_user_id>)

If you want to get parametrs by TwitchUser, you can use:

Parametrs.objects.filter(twitchuser__pk=<twitch_user_id>)

If you want to get Parametrs that have a Reward cost higher than 3, you can use:

Parametrs.objects.filter(skip__cost__gt=3)

If you want to get all TwitchUser objects that have a specific Reward with id 5, you can use:

TwitchUser.objects.filter(params__skip__pk=0)

Do these queries help?

  • Related