简体   繁体   中英

Django ManyToMany passing variables

I have started my Django project and I want to share some data between 2 classes. I'm not sure if I am doing it correctly. It works but i don't want to populate in my project bad practices. My code looks like this:

class Products(models.Model):
    name = models.CharField(max_length=50)
    protein = models.FloatField()
    carbohydrates = models.FloatField()
    fat = models.FloatField()
    food_type = models.CharField(max_length=6, choices=(
        ("1", "Meat"),
        ("2", "Fruit")
        )
    )
class Meals(models.Model):#Child
    name = models.CharField(max_length=50)
    ingredient = models.ManyToManyField(Products)

    def protein(self):
        protein = 0
        for ing in self.ingredient.all():
            protein += ing.protein
        return protein 

    @property
    def carbohydrates(self):
        carbohydrates = 0
        for ing in self.ingredient.all():
            carbohydrates += ing.carbohydrates
        return carbohydrates 

    def diet_category(self):        
        diet_types = "vegan, vegeterian, Keto, Paleo, Gluten-free"
        food_types = ""
        for ing in self.ingredient.all():
            food_types += ing.food_type
        if "1" in food_types: 
            diet_types.replace("vegan, ", "").replace(" vegeterian,", "")
        return (diet_types + " | " + food_types)

Additionally I have problem with .replace() function in python, which i want to use here to exclude some words from variable.

Summing up my questions are:

-Retrieving properties from another class is done by referring to an object of that class. In this case Products.objects.all()

-How can I remove words from variable in models.

-Should i use @property for functions which are returning values from another class?

Replace()

The replace() function returns a copy of the string with the replaced values. It will not change the original string.

So you need to do something like

diet_types = diet_types.replace("vegan, ", "")
diet_types = diet_types.replace("vegetarian, ", "")

Fetching values

You can loop like you do or use a query to achieve the same, somthing like:

def protein(self):
    return self.ingredient.aggregate(Sum('protein'))['protein__sum']

See the docs on aggregation for more details.

Properties

IMHO it is a matter of taste

Your classes can have properties dependent on other classes but make sure that you handle exception where there are no values found in other class. So I believe using @property is not a bad idea .

Moreover, did you try using

diet_types.replace("vegan, ", " vegeterian")

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