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.

Import foreign keys that do not exist (creating new values in Foreign key)

See original GitHub issue

I am trying to import values which do not already exist my foreign key. I would like import/export to add these new values to the ForeignKey model.

I’ve tried adding “null/blank” to the models, but it still will not create (import) new values in the foreign key. The error I get is “DoesNotExist: x matching query does not exist.”

Here is a sample of my Admin.py (which only imports to a foreign key if the values being imported already exist).

store_name = fields.Field(column_name='store_name', attribute='Store', widget=widgets.ForeignKeyWidget(Store, 'store_name'))
def clean(self, value):
        val = super(ForeignKeyWidget, self).clean(value)
        object, created = Store.objects.get_or_create(store_name='')
class Meta:
    model = Product
    fields = ('id', 'second_name', 'product_name', store',)
    export_order = ('id', 'second_name', 'product_name')
    skip_unchanged = False
    report_skipped = False
    widgets = {
            'published': {'format': '%d.%m.%Y'},
            }

Can anyone advise please?

Thanks

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:17 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
int-uacommented, Sep 14, 2015

I’ve written it this way:

class ForeignKeyWidgetWithCreation(ForeignKeyWidget):
    def __init__(
            self,
            model,
            field='pk',
            create=False,
            *args, **kwargs):
        self.model = model
        self.field = field
        self.create = create
        # super(ForeignKeyWidgetWithCreation, self).__init__(*args, **kwargs)

    def clean(self, value):
        val = super(ForeignKeyWidgetWithCreation, self).clean(value)
        if self.create:
            instance, new = self.model.objects.get_or_create(**{
                self.field: val
            })
            val = getattr(instance, self.field)
        return self.model.objects.get(**{self.field: val}) if val else None

Usage example

class SomeModelResource(Resource):
    field1 = fields.Field(
        attribute='field1',
        widget=ForeignKeyWidgetWithCreation(
            OtherModel,
            field='name',
            create=True))
Read more comments on GitHub >

github_iconTop Results From Across the Web

Foreign Key Constraint | CockroachDB Docs
The `FOREIGN KEY` constraint specifies a column can contain only values exactly matching existing values from the column it references.
Read more >
SQL insert foreign key if not exists - Stack Overflow
In MySQL, you can do this with just two statements: insert into groups (group_name) select s.group_name from (select :group_name as ...
Read more >
SQL Foreign key - SQLShack
In this article let us review different ways to create a SQL foreign key, rules on updates and deletes, enabling foreign key constraints, ......
Read more >
13.1.17.5 FOREIGN KEY Constraints - MySQL :: Developer Zone
Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if...
Read more >
An Essential Guide to MySQL Foreign Key By Practical ...
Once a foreign key constraint is in place, the foreign key columns from the ... a new row into the products table with...
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