У меня есть несколько Serialzers, независимо его нормально работает. Но при получении его в другом сериализаторе он выдает NameError: имя 'HostGroupSerializer' не определено
Получение ошибки Здесь в этой строке hostgroup = HostGroupSerializer (many = True, обязательно = False)
class MainHostSerializer(serializers.ModelSerializer):
group = serializers.PrimaryKeyRelatedField(queryset=HostGroup.objects.all(), many=True)
hostgroup = HostGroupSerializer(many=True, required=False)
class Meta:
model = MainHost
fields = (
'host_id',
'host_name',
'inventory',
'group'
)
depth = 2
def create(self, validated_data):
hostgroup_data = validated_data.pop('hostgroup')
group = validated_data.pop('group')
host = MainHost.objects.create(**validated_data)
for hostgroup in person_data:
d=dict(group)
HostGroup.objects.create(host=host, group=d['group'])
return host
class Meta:
model = MainHost
fields = (
'host_id',
'host_name',
'inventory',
'group'
)
HostGroupSerializer.py, его сериализатор таблицы полей Many2Many. Создается как сквозное поле в Parent.
class HostGroupSerializer(serializers.ModelSerializer):
host = MainHostSerializer()
group = MainGroupSerializer()
class Meta:
model = HostGroup
fields = (
'id',
'host',
'group'
)
read_only_fields = ['host', 'group']
def create(self, validated_data):
host_data = MainHost.objects.create(**validated_data.get('host'))
group_data = MainGroup.objects.create(**validated_data.get('group'))
conn = HostGroup.objects.create(
host=host_data,
group=group_data
)
return conn
Модель HostGroup
class HostGroup(models.Model):
host = models.ForeignKey(MainHost, on_delete=models.CASCADE)
group = models.ForeignKey(MainGroup, on_delete=models.CASCADE)
Модель MainHost с полем Many2Many
class MainHost(models.Model):
host_id = models.IntegerField(verbose_name='HOST ID', primary_key=True)
host_name = models.CharField(verbose_name='HOST NAME', max_length=512)
inventory = models.ForeignKey(related_name='inv_ins', on_delete=models.SET_NULL, to='hosts.MainInventory', blank=True, null=True)
group = models.ManyToManyField(MainGroup, related_name='hostgroups', through ='HostGroup')