简体   繁体   中英

Django related objects in hierarchy

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?

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.

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