Перегруппировать Queryset от ManyToManyField - PullRequest
0 голосов
/ 01 июня 2019

Я работаю с django, и мне нужно восстановить записи модели с именем Restaurante, у которой есть такие атрибуты, как Имя, Адрес, Телефон, Город и т. Д., А также имеет атрибут food_type, который представляет собой ManyToManyFiel, с моей моделью под названием FoodType, потому что в ресторане вы можете подавать много видов еды (например, мексиканскую, итальянскую, веганскую и т. д.) и тип еды, это может быть предложено во многих ресторанах, и я хочу восстановить все рестораны в X городе и сгруппируйте их по типам питания следующим образом:

  1. Веганская еда
    • Компостера
    • Натуральные продукты
    • GreenRestaurant
    • Resto Bar
  2. итальянская еда
    • Resto Bar
    • Piere Pizzas
    • Компостера
  3. мексиканская еда
    • Jalisquitos
    • Майя Тако
    • GreenRestaurant

Я пытался сделать это с тегом {% regroup%}, но он показывает ожидаемый результат, я прилагаю код моделей:

class FoodType(models.Model):
    name = models.CharField(
        max_length = 150,
        blank = False,
        null = False,
        help_text = 'Enter the name of the type of food',
        verbose_name = 'Name'
    )
    description = models.CharField (
        max_length = 250,
        blank = False,
        null = False,
        help_text = 'Enter a brief description of this type of food',
        verbose_name = 'Description'
    )

class Restaurant(models.Model):
    name = models.CharField (
        max_length = 50,
        blank = False,
        null = False,
        help_text = 'Enter the name of the restaurant',
        verbose_name = 'Restaurant Name',
    )
    address = models.CharField (
        max_length = 200,
        blank = False,
        null = True,
        help_text = 'Enter the physical address of the restaurant',
        verbose_name = 'Addres'
    )
    telefono = PhoneNumberField(
        null = False,
        help_text = 'Enter the phone number of the restaurant in the format +999999999',
        unique = True,
        verbose_name = 'Phone Number'
    )
    city = models.ForeignKey(
        City,
        related_name = 'ubica_en',
        on_delete = models.DO_NOTHING,
        blank = False,
        null = True,
        help_text = 'Select the city to which this restaurant belongs',
        verbose_name = 'City',
    )
    administrator = models.ForeignKey(
        User,
        related_name = 'es_registrado_por',
        on_delete = models.CASCADE,
        blank = False,
        null = False,
        help_text = 'User who added this restaurant',
        verbose_name = 'Who registered it?'
    )
    food_type = models.ManyToManyField(
        FoodType,
        help_text = 'Select the type (s) of food served in this restaurant',
        related_name = 'restaurants',
        verbose_name = 'Type of food',
        blank = False
    )

Я прикрепляю код с тегом {% regroup%}:

{% regroup restaurants by food_type as food_type_list %}
{% for food_type in food_type_list %}
  {{ food_type.grouper }}
  {% for restaurant in food_type.list %}
    <h1>{{ restaurant|upper }}</h1>
  {% endfor %}
{% endfor %}

Я надеюсь, что вы можете помочь мне заранее, большое спасибо.

1 Ответ

0 голосов
/ 04 июня 2019

В итоге я решил это следующим образом:

foods = FoodType.objects.all()
group = {}
for food in foods:
    restaurant_key = '_'.join([str(restaurant.pk) for restaurant in comida.restaurant_set.all()])
    if not restaurant_key in group and restaurant_key! = '':
        group[restaurant_key] = {'restaurants': food.restaurant_set.all(), 'foods': []}
    if restaurant_key! = '':
        group[restaurant_key]['foods'].append(food)
context ['group'] = group
...