question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to import related objects and their relationships.

See original GitHub issue

When I import models like following:

class Category(models.Model):
   name = models.CharField(max_length=100, db_index=True)

class Subcategory(models.Model):
   name = models.CharField(max_length=100, db_index=True)
   slug = models.SlugField(max_length=200, db_index=True)
   category = models.ForeignKey(Category, blank=True)

class Product(models.Model):
   name = models.CharField(max_length=100) 
   category = models.ForeignKey(Category, blank=True, null=True)
   subcategory = models.ForeignKey(Subcategory, blank=True, null=True)

Everything is imported thanks to ForeignKeyWidget, but how can I import relations when my csv file looks something like that:

id | product_name | category | subcategory – | T-Shirt A | His | summer – | T-Shirt B | Her | summer

?

As you see ‘summer’ subcategory name isn’t unique and I need to set the proper relationship like:

‘His’ < ‘summer’ < ‘T-Shirt A’ ‘Her’ < ‘summer’ < ‘T-Shirt A’

during import.

How can I achieve it?

I will be grateful for your help.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
gthielebcommented, Feb 14, 2017

I have solved this in my current project (for importing ManyToMany Values) with subclassing import_field and calling a clean_FOO method (adapted the code from dehydrate_FOO). Within the clean method (example here are ManyToMany fields disks and filesystems) you can get the correct subcategory or create the instance with Django’s get_or_create method (Careful about the return values here).

class SpecResource(resources.ModelResource):

    disks = fields.Field(column_name='Disks')
    filesystems = fields.Field(column_name='Filesystems')

    class Meta:
	model = Spec
	exclude = []

    def import_field(self, field, obj, data):

	field_name = self.get_field_name(field)
	method = getattr(self, 'clean_%s' % field_name, None)
	if method is not None:
	    obj = method(field, obj, data)

        super(SpecResource, self).import_field(field, obj, data)


    def clean_disks(self, field, obj, data):

	disks = []
	cell = data[field.column_name]
	for e in cell.split(','):
	    e = e.strip().split('-')
	    if len(e) < 3:
	        continue
	    size, disk_type, quality = e
	    qualityi, created = StorageQuality.objects.get_or_create(quality=quality)
	    diski, created = Disk.objects.get_or_create(size=size, disk_type=disk_type, quality=qualityi)
	    disks.append(diski)
	obj.disks = disks
	return obj

    def clean_filesystems(self, field, obj, data):

	filesystems = []
	cell = data[field.column_name]
	for e in cell.split(','):
	    e = e.strip().split('-')
	    if len(e) < 3:
	        continue
	    mount, size, quality = e
	    qualityi, created = StorageQuality.objects.get_or_create(quality=quality)
	    filesystemi, created = Filesystem.objects.get_or_create(mount=mount, size=size, quality=qualityi)
	    filesystems.append(filesystemi)
	obj.filesystems = filesystems
	return obj
0reactions
stale[bot]commented, Feb 11, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Migrate data from one organization to another - Salesforce Help
The easiest way to do this is using Excel's VLOOKUP function to add the new record Ids to your files for import.
Read more >
Import and Export records with lookup or master detail ...
Hello Trailblazers, In this video we're going to learn how we can import or export records with lookup or master detail relationships in ......
Read more >
Import Your Relationship Data - Oracle Help Center
Attribute Description Prerequisite Setup Task/ Import V... StartDate The date when the relationship was created. This should be a valid date. EndDate The date when...
Read more >
How to preserve relationships upon data import?
First you can't import primay Ids in Salesforce. They are always automatically generated on insert. For the relation you need to export the ......
Read more >
Salesforce Object Relationships - Workato Docs
An object relationship in Salesforce is a two-way association between two objects. Relationships are created by creating custom relationship fields on an object...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found