Создание записи дочерней таблицы при создании новой записи родительской таблицы

У меня эта модель:

В этом решении, когда я создаю новый Profile, создается новый Rank. Это работает. Однако, когда я создаю новую запись Command, требуется новая запись CommandPositions. Я попробовал сделать это так же, как и отношения Profile/Rank, но выдает ошибку, говоря, что ее нет.

Почему Profile/Rank работает, а Command/CommandPositions говорит, что я не могу этого сделать?

Любая мудрость будет высоко оценена. Спасибо!

Consider your two different cases:

rank = Rank.objects.create(user=self, longrank='o1', shortrank='o1', branch='r')
rank.save()
CommandPositions = CommandPositions.objects.create(command=self, name="CO", responsibility='Commanding Officer')
CommandPositions.save()

Notice anything different?

It's subtle, and there's a missing piece:

class CommandPositions(models.Model):

So what your code essentially does, is you're trying to bind a variable (CommandPositions the variable in .save()) to a name that's already in use (CommandPositions the class definition). Python interpreter thinks you're off your rocker, so it ignores this, because otherwise many other bad things will happen.

The fix

# Or pick any variable name you want 
# as long as it's not something already in use in this scope
command_positions = CommandPositions.objects.create(command=self, name="CO", responsibility='Commanding Officer')
command_positions.save()
Вернуться на верх