1

I've got some models which relations like this:

class Conversion(models.Model):

    class Unit(models.IntegerChoices):
        g   = 10, 'gramy',
        ml  = 20, 'mililitry',
        qty = 30, 'sztuki'

    name = models.CharField(max_length=128)
    g = models.FloatField()
    ml = models.FloatField(null=True, blank=True)
    qty = models.FloatField(null=True, blank=True)
    default = models.IntegerField(choices=Unit.choices, default=Unit.g)

class Ingredient(models.Model):

    class Unit(models.IntegerChoices):
        g   = 10, 'gramy',
        dkg = 11, 'dekagramy',
        kg  = 12, 'kilogramy',
        ml  = 20, 'mililitry',
        l   = 21, 'litry',
        qty = 30, 'sztuki'

    Conversion = models.ForeignKey(Conversion, on_delete=models.CASCADE, related_name='ingredients')
    amount = models.FloatField()
    unit = models.IntegerField(choices=Unit.choices, default=Unit.g)

class Step(models.Model):
    body = models.JSONField()
    Ingredients = models.ManyToManyField(Ingredient, related_name='steps')

class Recipe(models.Model):
    title = models.CharField(max_length=128)
    teaser = models.CharField(max_length=256)
    Steps = models.ManyToManyField(Step, blank=True, related_name='recipes')

Say there's a conversion for flour where 1ml == .53g, and the steps are separated because of how they are displayed so I thought it would be best to put it all into separate models.

Is there a way to search for a recipe that has steps with Ingredient.Conversion.pk == x and Ingredient.amount >= y?

I've read about related objects but can I use them in this kind of relation, should I use some inner join or is there any other way I could use Django to filter it easily?

2
  • Yes you can traverse through relations while filtering using the ORM. Please add your models to the question. Commented Mar 14, 2021 at 15:55
  • @AbdulAzizBarkat Here you go! Commented Mar 14, 2021 at 16:06

1 Answer 1

1

You can traverse through relations in a query using __. Also for checking if a value is greater than equal to something one uses __gte. Your query would become something like:

conversion_pk = # some pk of conversion
ingredient_amount = # ingredient amount
Recipe.objects.filter(Steps__Ingredients__Conversion__pk=conversion_pk, Steps__Ingredients__amount__gte=ingredient_amount)

Note: Ideally attribute / variable names should be in snake_case not PascalCase so steps instead of Steps, ingredients instead of Ingredients, etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.