Giter Club home page Giter Club logo

Comments (6)

matthewhegarty avatar matthewhegarty commented on June 14, 2024

Thanks for raising. I couldn't reproduce with the example app. I created a test branch here.

I added this code to the Book model:

image

I ran the new migrations and then tried to import with the attached file. The import worked fine for me.

books_with_generatedfield.csv

Is it possible you can reproduce using the branch and example file? Or perhaps you can give me clearer steps to reproduce?

from django-import-export.

uncountablereals avatar uncountablereals commented on June 14, 2024

Slightly adjusted tables below

class OperationsExportShipments(models.Model):
    shipment_id = models.CharField(primary_key=True)
    shipment_status = models.ForeignKey(OperationsExportShipmentsStatuses, models.DO_NOTHING, db_column='shipment_status')
    checked_in = models.BooleanField()
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)
    fba_shipment = models.OneToOneField(FbaShipments, models.DO_NOTHING, db_column='fba_shipment',null=True,blank=True)
    walmart_shipment = models.OneToOneField(WalmartShipments, models.DO_NOTHING, db_column='walmart_shipment',null=True,blank=True)
    shipment_carrier = models.ForeignKey(WarehouseCarriers, models.DO_NOTHING, db_column='shipment_carrier',null=True,blank=True)
    mock_generated_column =   models.GeneratedField(
        expression=RawSQL("1", []),
        output_field=models.IntegerField(),
        db_persist=True
    )

    
    class Meta:
        managed = True
        db_table = 'operations_export_shipments'
        
        #contraint that exactly one of fba_shipment or walmart_shipment must be set
        constraints = [
            models.CheckConstraint(
                check=(
                    (Q(fba_shipment__isnull=False) & Q(walmart_shipment__isnull=True)) |
                    (Q(fba_shipment__isnull=True) & Q(walmart_shipment__isnull=False))
                ),
                name='check_fba_walmart_shipment_exclusivity'
            ),
            #constraint that checked_in can only be True if shipment_status is 'ARRIVED'
            models.CheckConstraint(
                check=(
                    Q(checked_in=False) | 
                    (Q(checked_in=True) & Q(shipment_status='ARRIVED'))
                ),
                name='check_checked_in_with_status_arrived'
            )
        ]

class OperationsExportShipmentsResource(resources.ModelResource):
    class Meta:
        model = OperationsExportShipments
        fields = (
            "fba_shipment","walmart_shipment",
            "shipment_status",
            "checked_in"
        )

    def before_import_row(self, row, **kwargs):
        """
        Override this method to add logic before saving an instance.
        Use this to determine if a row corresponds to an FBA shipment or Walmart shipment and handle accordingly.
        """
        row["shipment_status"] = row["shipment_status"].upper().replace(" ","_")
        if not row["fba_shipment"]:
            row["fba_shipment"] = None
        if not row["walmart_shipment"]:
            row["walmart_shipment"] = None

        if row["checked_in"].lower().strip() == "yes":
            row["checked_in"] = True
        elif row["checked_in"].lower().strip() == "no":
            row["checked_in"] = False
        else:
            row["checked_in"] = None
        print(row)
        super().before_import_row(row, **kwargs)



    def get_instance(self, instance_loader, row):
        """
        Override to custom handle identifying existing instances.
        """
        # print(row)
        # self.Meta.model.objects.get(fba_shipment=row['fba_shipment'],
                                           # walmart_shipment=row['walmart_shipment'])
        print("stage 2")
        try:

            return self.Meta.model.objects.get(fba_shipment=row['fba_shipment'],
                                                walmart_shipment=row['walmart_shipment'])
        except self.Meta.model.DoesNotExist:
            print("no instance foudn!")
            return None        

When I upload a csv with a new row on this, I get the following error:

Line number: 6 - Save with update_fields did not affect any rows.

Traceback (most recent call last):
File .../.venv/lib/python3.10/site-packages/import_export/resources.py", line 817, in import_row
self.save_instance(instance, new, using_transactions, dry_run)
File ".../.venv/lib/python3.10/site-packages/import_export/resources.py", line 528, in save_instance
instance.save()
File "...models.py", line 598, in save
super().save(*args, **kwargs)
File .../django/db/models/base.py", line 814, in save
self.save_base(
File  .../django/db/models/base.py", line 901, in save_base
updated = self._save_table(
File ...django/db/models/base.py", line 1034, in _save_table
raise DatabaseError("Save with update_fields did not affect any rows.")
django.db.utils.DatabaseError: Save with update_fields did not affect any rows.

So the updated rows were fine with the import, but there was an issue with the new row.

Now I comment out the generated column

class OperationsExportShipments(models.Model):
    shipment_id = models.CharField(primary_key=True)
    shipment_status = models.ForeignKey(OperationsExportShipmentsStatuses, models.DO_NOTHING, db_column='shipment_status')
    checked_in = models.BooleanField()
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)
    fba_shipment = models.OneToOneField(FbaShipments, models.DO_NOTHING, db_column='fba_shipment',null=True,blank=True)
    walmart_shipment = models.OneToOneField(WalmartShipments, models.DO_NOTHING, db_column='walmart_shipment',null=True,blank=True)
    shipment_carrier = models.ForeignKey(WarehouseCarriers, models.DO_NOTHING, db_column='shipment_carrier',null=True,blank=True)
    # mock_generated_column =   models.GeneratedField(
    #     expression=RawSQL("1", []),
    #     output_field=models.IntegerField(),
    #     db_persist=True
    # )

And the upload is fine

image

from django-import-export.

matthewhegarty avatar matthewhegarty commented on June 14, 2024

Thanks - I can reproduce when uploading a new row.

from django-import-export.

matthewhegarty avatar matthewhegarty commented on June 14, 2024

Have raised as Django issue

from django-import-export.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.