Home > Software engineering >  The problem with adding data to Many To Many Django
The problem with adding data to Many To Many Django

Time:09-08

I want to add data to Many To Many. The api_data variable receives data from the API. I'm starting to process them. Instead of set, I also tried add. Nothing helps. I don't know what's wrong

def write_add_serv_to_stations() -> None:
    stations_arr = []
    for data in api_data:
        additional_ids = data['serviceIds'].split(',') if data['serviceIds'] else [85]
        for additional_id in additional_ids
                services = Services.objects.filter(id=1)
                additional = Additional.objects.filter(id__in=[additional_id])
                station = Stations.objects.filter(station_id=data['id'])
                stations = Stations(service=station.service.set(services),
                                    additional=station.additional.set(additional))
                stations_arr.append(stations)
    Stations.objects.bulk_update(stations_arr)

An error comes out

Traceback (most recent call last):
  File "C:\Users\Ramil\AppData\Local\Programs\Python\Python310\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "D:\Work\Django_work\Locator\projects\locator\parsing.py", line 88, in write_add_serv_to_stations
    stations = Stations(service=station.service.set(services),
  File "D:\Work\Django_work\Locator\projects\venv\lib\site-packages\django\db\models\base.py", line 582, in __init__
    _setattr(self, prop, value)
  File "D:\Work\Django_work\Locator\projects\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 606, in __set__
    raise TypeError(
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use service.set() instead.

I've sorted through everything that is possible and impossible, I can't understand what the error is. Here are the models

class Services(models.Model):
    id = models.PositiveIntegerField(primary_key=True, verbose_name='id')
    name = models.CharField(max_length=50, verbose_name="Название")

    class Meta:
        verbose_name_plural = "Типы топлива"


class Additional(models.Model):
    id = models.PositiveIntegerField(primary_key=True)
    name = models.CharField(max_length=100, verbose_name='Дополнительные услуги')


class Stations(models.Model):
    service = models.ManyToManyField(Services, verbose_name='Название топлива', null=True, blank=True)
    additional = models.ManyToManyField(Additional, verbose_name='Услуги', null=True, blank=True)

Please help with the problem!

CodePudding user response:

You must create a Station instance first and then add the many to many fields inside the instance.

stations_arr = []
for additional_id in additional_ids:
    ....
    services = Services.objects.filter(id=1)
    additional = Additional.objects.filter(id__in=[additional_id])
    stations = Stations.objects.get(id=id)
    stations.service.add(services)
    stations.additional.add(additional)
    station.save()

I haven't tried this in your code but this should get you started on your solution.

  • Related