@vadik007

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use location_id.set() instead?

Добрый день! Столкнулся с такой проблемой при загрузке данных в джанго - TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use location_id.set() instead.
Прочитал про похожую ситуацию вот здесь, но так и не понял как и где использовать location_id.set(). Подскажите пожалуйста как можно решить проблему

Вот моя модель
from django.db import models

# Create your models here.


class Location(models.Model):
    name = models.CharField(max_length=150)
    lat = models.DecimalField(decimal_places=4, max_digits=6, null=True)
    lng = models.DecimalField(decimal_places=4, max_digits=6, null=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Локация'
        verbose_name_plural = 'Локации'


class User(models.Model):
    ROLES = [
        ("member", "Пользователь"),
        ("moderator", "Модератор"),
        ("admin", "Админ"),
    ]


    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    username = models.CharField(max_length=150)
    password = models.CharField(max_length=150)
    role = models.CharField(max_length=50, choices=ROLES, default='member')
    age = models.IntegerField
    location_id = models.ManyToManyField(Location)

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'


Вот скрипт загрузки
from csv import DictReader
from django.core.management import BaseCommand

# Import the model
# from children.models import children
from users.models import User
ALREDY_LOADED_ERROR_MESSAGE = """
If you need to reload the child data from the CSV file,
first delete the db.sqlite3 file to destroy the database.
Then, run `python manage.py migrate` for a new empty
database with tables"""


class Command(BaseCommand):
    # Show this when the user types help
    help = "Loads data from children.csv"

    def handle(self, *args, **options):

        # Show this if the data already exist in the database
        if User.objects.exists():
            print('child data already loaded...exiting.')
            print(ALREDY_LOADED_ERROR_MESSAGE)
            return

        # Show this before loading the data into the database
        print("Loading childrens data")

        # Code to load the data into database
        for row in DictReader(open('./datasets/user.csv', encoding='utf-8')):
            child = User.objects.create(
                        first_name=row['first_name'],
                        last_name=row['last_name'],
                        username=row['username'],
                        password=row['password'],
                        role=row['role'],
                        age=row['age'],
                        location_id=row['location_id']
            )
  • Вопрос задан
  • 1949 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы