Не удается заставить мой сериализатор прочитать мой гнездовой список объектов

#django #django-models #django-rest-framework

#django #django-модели #django-rest-framework

Вопрос:

Я все еще новичок в Django, и я рву на себе волосы из-за этой проблемы. Я получаю объект JSON от внешнего API. Который я пытаюсь сохранить в нашей базе данных из Django. Вот пример объекта JSON.

     {
"A bunch of Keys": "and values",
"Units": [
         "Year": "2020",
         "Make": "Jay Flight SLX",
         "ETC" : "ETC"
         "Parts": [
                {
                    "DealerId": "",
                    "MajorUnitPartsId": 10187618,
                    "PartNumber": "06-0544",
                    "SupplierCode": "672",
                    "Qty": 1,
                    "Cost": 37.95,
                    "Price": 0.0,
                    "Retail": 37.95,
                    "SetupInstall": "I",
                    "Description": "20# PROPANE COVER BLACK",
                    "dealstate": 5,
                    "internaltype": 2
                },
                {
                    "DealerId": "",
                    "MajorUnitPartsId": 9637201,
                    "PartNumber": "0274320",
                    "SupplierCode": "JAY",
                    "Qty": 1,
                    "Cost": 0.92,
                    "Price": 4.99,
                    "Retail": 4.99,
                    "SetupInstall": "I",
                    "Description": "BATTEN,HENDRIX BEACH .88X8' CP2",
                    "dealstate": 5,
                    "internaltype": 4
                },
  ]
   "Trade": [
        {
            "DealerId": "",
            "StdMake": "COBRA",
            "StdModel": "31",
            "StdYear": "1993",
            "StdCategory": "",
            "allowance": 3000.0,
            "acv": 500.0,
            "payoff": 0.0,
            "lienholder": "",
            "modelname": "",
            "unitclass": "C",
            "color": "",
            "odometer": 0,
            "manufacturer": "PASSPORT",
            "note": "",
            "unittype": "CLASS C"
        }
{
  

Теперь проблема, с которой я сталкиваюсь, заключается в том, что когда запускается мой сериализатор, я хочу открыть каждый список, а затем сохранить их в своих собственных модулях. Работает основная таблица, работает таблица единиц измерения и работает таблица торговли. Однако при попытке открыть мой список деталей я продолжаю получать эту ошибку ->
part_data = validated_data[«Единицы измерения»].pop(«Части»)
(Pdb) n
Ошибка типа: объект ‘str’ не может быть интерпретирован как целое число

Ниже приведены мои сериализаторы и мои таблицы для деталей и узлов, потому что у меня есть внешний ключ, который нужно указать для привязки к этой таблице. Любая помощь была бы отличной!

     class SalesDealDetailUnitsPartsSerializer(serializers.ModelSerializer):
    class Meta:
        model = SalesDealDetailUnitsParts
        fields = ['DealerId', "PartNumber", "SupplierCode", "Qty", "Cost", "Price", "Retail", "SetupInstall", "Description", "dealstate", "internaltype"] 
        depth = 1


class SalesDealDetailUnitsSerializer(serializers.ModelSerializer):
    Parts = SalesDealDetailUnitsPartsSerializer(many=True)
    class Meta:
        model = SalesDealDetailUnits
        fields = '__all__'
        depth = 1


class SalesDealDetailTradeSerializer(serializers.ModelSerializer):
    class Meta:
        model = SalesDealDetailTrade
        fields = '__all__'
        depth = 1


class SalesDealDetailSerializer(serializers.ModelSerializer):
    Trade = SalesDealDetailTradeSerializer(many=True)
    Units = SalesDealDetailUnitsSerializer(many=True)

    class Meta:
        model = SalesDealDetail
        fields = '__all__'

    def create(self, validated_data):
        pdb.set_trace()
        unit_data = validated_data.pop("Units")
        part_data = unit_data.pop("Parts")
        trade_data = validated_data.pop("Trade")
        sales_deal = SalesDealDetail.objects.create(**validated_data)
        for unit in unit_data:
            SalesDealDetailUnits.objects.create(SalesDeal=sales_deal, **unit)
        for part in part_data:
            SalesDealDetailUnitsParts.objects.create(Parts=unit_data, **part)
        # for stuff in unit_data:
        #     part_data = unit_data.pop('Parts')
        #     each_item_instance = SalesDealDetailUnits.objects.create(SalesDeal=sales_deal, **stuff)
        #     for parts in part_data:
        #         SalesDealDetailUnitsParts.objects.create(DealUnit=unit, **parts)
        for trade in trade_data:
            SalesDealDetailTrade.objects.create(SalesDeal=sales_deal,  **trade)
        return sales_deal

    def update(self, instance, validated_data):
        unit_data = validated_data.pop('Units')
        units = (instance.Units).all()
        units = list(units)

        part_data = unit_data.pop('Parts')
        parts = (instance.Units.Parts).all()
        parts = list(parts)

        trade_data = validated_data.pop('Trade')
        trades = (instance.Trade).all()
        trades = list(trade)

        [setattr(instance, k, v) for k, v in validated_data.items()]

        instance.save()

        for u in unit_data:
            try:
                pk = u.get('DealUnitId')
                unit = SalesDealDetailUnits.objects.get(DealUnitId=pk)
                [setattr(unit, k, v) for k, v in unit.items()]
                unit.save()
            except:
                SalesDealDetailUnits.objects.create(SalesDeal=instance, **unit)
            for p in part_data:
                try:
                    pk = p.get('PartNumber')
                    part = SalesDealDetailUnitsParts.objects.get(PartNumber=pk)
                    [setattr(part, k, v) for k, v in p.items()]
                    part.save()
                except:
                    SalesDealDetailUnitsParts.objects.create(DealUnit=u, **part)

        for t in trade_data:
            try:
                pk = t.get('DealTradeId')
                trade = SalesDealDetailTrade.objects.get(DealTradeId=pk)
                [setattr(trade, k, v) for k, v in trade.items()]
                trade.save()
            except:
                SalesDealDetailTrade.objects.create(SalesDeal=instance, **trade)
  

Вот таблицы единиц измерения и деталей

 class SalesDealDetailUnits(models.Model):
    SalesDeal = models.ForeignKey(SalesDealDetail, related_name='Units', on_delete=models.CASCADE)
    DealerId = models.CharField(max_length=255, blank=True, null=True)
    DealUnitId = models.IntegerField(primary_key=True)
    Newused = models.CharField(max_length=255, blank=True, null=True)
    Year = models.CharField(max_length=255, blank=True, null=True)
    Make = models.CharField(max_length=255, blank=True, null=True)
    Model = models.CharField(max_length=255, blank=True, null=True)
    VIN = models.CharField(max_length=255, blank=True, null=True)
    Class = models.CharField(max_length=255, blank=True, null=True)
    Unitprice = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    mucost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Freight = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Freightcost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Handling = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Handlingcost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    LicFees = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    LicFeesCost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Totaccy = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Totinstall = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Tradeall = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Tradeacv = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Accycost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    Installcost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    docfees = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    actualcost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    DateReceived = models.DateTimeField(blank=True, null=True)
    servcont = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    sccost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    propliab = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    plcost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    PackAmt = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    HoldbackAmt = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    unittype = models.CharField(max_length=255, blank=True, null=True)
    SalesType = models.CharField(max_length=255, blank=True, null=True)
    UnitSoldPrice = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitSoldCost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    TotalPartsAmount = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    DaysInStore = models.IntegerField(blank=True, null=True)
    UnitLine1 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine2 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine3 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine4 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine5 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine6 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine7 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine8 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine9 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine10 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine11 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine12 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine13 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine14 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine15 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine16 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine17 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine18 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine19 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine20 = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine1cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine2cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine3cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine4cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine5cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine6cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine7cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine8cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
    UnitLine9cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine10cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine11cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine12cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine13cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine14cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine15cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine16cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine17cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine18cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine19cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
UnitLine20cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
Color = models.CharField(max_length=255, blank=True, null=True)
Odometer = models.CharField(max_length=255, blank=True, null=True)
stocknumber = models.CharField(max_length=255, blank=True, null=True)
deposit = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
bodytype = models.CharField(max_length=255, blank=True, null=True)
enginenumber = models.CharField(max_length=255, blank=True, null=True)
cylinders = models.CharField(max_length=255, blank=True, null=True)
gvwr = models.CharField(max_length=255, blank=True, null=True)
fueltype = models.CharField(max_length=255, blank=True, null=True)
majorunitsalescategory = models.CharField(max_length=255, blank=True, null=True)
Vehicletaxtotal = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
Taxableamounttotal = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
Totaltax = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
servcontterm = models.IntegerField(blank=True, null=True)
unitline4term = models.CharField(max_length=255, blank=True, null=True)
unitline5term = models.CharField(max_length=255, blank=True, null=True)
unitline6term = models.CharField(max_length=255, blank=True, null=True)
unitline10term = models.CharField(max_length=255, blank=True, null=True)
unitline11term = models.CharField(max_length=255, blank=True, null=True)
unitline12term = models.CharField(max_length=255, blank=True, null=True)
plateno = models.CharField(max_length=255, blank=True, null=True)
customerunitid = models.IntegerField(blank=True, null=True)
packageid = models.IntegerField(blank=True, null=True)
unitid = models.CharField(max_length=255, blank=True, null=True)
modelname = models.CharField(max_length=255, blank=True, null=True)
# Parts = models.ManyToManyField(SalesDealDetailUnitsParts, related_name='Parts')

def __str__(self):
    return f"{self.DealUnitId}"


class SalesDealDetailUnitsParts(models.Model):
Unit = models.ForeignKey(SalesDealDetailUnits, related_name='Parts', default="", 
on_delete=models.CASCADE)
DealerId = models.CharField(max_length=255, blank=True, null=True)
PartNumber = models.CharField(max_length=255, primary_key=True)
SupplierCode = models.CharField(max_length=255, blank=True, null=True)
Qty = models.IntegerField(blank=True, null=True)
Cost = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
Price = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
Retail = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True)
SetupInstall = models.CharField(max_length=255, blank=True, null=True)
Description = models.CharField(max_length=255, blank=True, null=True)
dealstate = models.IntegerField(blank=True, null=True)
internaltype = models.IntegerField(blank=True, null=True)

def __str__(self):
    return f"{self.PartNumber}"
  

Комментарии:

1. Не могли бы вы опубликовать всю трассировку стека?

2. > c:usersshawndocumentsrvx1rvxevoserializers.py (201)создать() -> unit_data = validated_data.pop(«Единицы измерения») (Pdb) n > c:usersshawndocumentsrvx1rvxevoserializers.py (202)create() -> part_data = unit_data.pop(«Части») (Pdb) n Ошибка типа: объект ‘str’ не может быть интерпретирован как целое число> c:usersshawndocumentsrvx1rvxevoserializers.py (202)создать() -> part_data = unit_data.pop(«Части»)

Ответ №1:

Я вижу Units список. Вы не можете этого сделать list.pop("some_string") . Вы должны сделать list[0].pop("some_string") . Или сделайте что-то подобное для каждого объекта в списке.