简体   繁体   中英

how to store a list into many-to-many field in django model

I have a model class dietplan in which there is a many-to-many field named breakfast. In my view.py I have done some calculation and get a value for breakfast as nested list ie [['abc','asda'],['val3','val4']]

I want to these all 4 list in my many to many field.

This is my code:

MODELS.PY\

class Dietplan(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dietplan_name = models.CharField(max_length=255, null=True)
    breakfast = models.ManyToManyField('Meal', 
    related_name='breakfast_meal_name',)
    snacks1 = models.ManyToManyField('Meal', 
    related_name='snacks1_meal_name',)
    lunch = models.ManyToManyField('Meal', related_name='lunch_meal_name',)
    snacks2 = models.ManyToManyField('Meal', 
    related_name='snacks2_meal_name',)
    dinner = models.ManyToManyField('Meal', related_name='dinner_meal_name',)
    calories_slab = models.IntegerField(blank=True, null=True)

VIEWS.PY

def dietplan(request):
    d = Dietplan.objects.get(id = request.user.id)
    d.dietplan_name = 'abc'
    d.breakfast.set(','.join(breakfast))
    d.save()

Showing unhashable list type error

Assuming Meal objects already exists, first you should get them from their name. You can try something like:

meal_names = 'meal1 meal2 meal3'.split()
meal_objects = []
for name in meal_names:
    meal_objects.append(Meal.objects.get(name=name))

once you have collected them, you can append them in your manytomany relation as follow:

d = Dietplan.objects.get(id = request.user.id)
d.breakfast.add(*meal_objects)  # unpacking meal_objects list as positional arguments
d.save()

Note: I have not tested the code in django, let me know this raise some errors.

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