Comments (6)
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:
I ran the new migrations and then tried to import with the attached file. The import worked fine for me.
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.
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
from django-import-export.
Thanks - I can reproduce when uploading a new row.
from django-import-export.
Have raised as Django issue
from django-import-export.
Related Issues (20)
- error in admin model actions HOT 1
- Unknown documents in resources.py if you use a intersphinx setup
- Custom Import Form: Bug when form fields are also in Resource.import_id_field HOT 3
- Test needed to cover `collect_failed_row` option HOT 4
- 'list' object is not callable HOT 2
- ImproperlyConfigured at /admin/.. HOT 2
- Failing test in different python environments
- skip_row doesn't work correctly HOT 15
- The error message for invalid column names is misleading
- Export the excel as password protected file HOT 3
- `is_create` param should be passed into new `do_instance_save()` method
- `SimpleArrayWidget.render()` crashes if value is None
- Djangonaut Space navigator interest
- how to skip error for confirm: '"Field 'id' expected a number but got '1-variant'. " HOT 2
- Not able to export to xls with UUIDs HOT 2
- Support dynamic selection of Resource class based on request property
- Remove support for django3.2
- Add type hints HOT 3
- Confirmation page displays incorrect fields
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-import-export.