scythargon
scythargon

Reputation: 3491

Django model save self.field.rel.to.DoesNotExist

I found several times(one, two) that people do the same things that I do:

class TempUser(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    bank_account = models.ForeignKey(BankAccount)

    def save(self, *args, **kwargs):
        if not self.bank_account:
            bank_account = BankAccount()
            bank_account.save()
            self.bank_account = bank_account
        super(TempUser, self).save(*args, **kwargs)

But I got next exception:

 File "models.py", line 134, in main
    fill_predefined_data()
  File "models.py", line 121, in fill_predefined_data
    user.save()
  File "models.py", line 41, in save
    if not self.bank_account:
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 343, in __get__
    raise self.field.rel.to.DoesNotExist
__main__.DoesNotExist

Upvotes: 2

Views: 2230

Answers (4)

Suganthi
Suganthi

Reputation: 417

Seems like bank_account is not created. Do you have any mandatory fields in BankAccount?

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

I'm not sure why you think either of those links are relevant. Both of them access normal fields on the model - id and char fields. You are accessing a ForeignKey, which of course is a reference to another model instance that may or may not exist. In your case, it clearly doesn't exist.

The easiest thing to do is to check for the FK id rather than the actual object:

    if not self.bank_account_id:
        bank_account = BankAccount()
        bank_account.save()
        self.bank_account = bank_account

Upvotes: 0

Christian Thieme
Christian Thieme

Reputation: 1124

You may either change your TempUser model

bank_account = models.ForeignKey(BankAccount, null=True)

or change your condition to:

if not hasattr(self, 'bank_account'):

Upvotes: 3

EsseTi
EsseTi

Reputation: 4271

Not sure but probably the problem is with the fact that the TempUser is not created yet.

One thing you can do is to use pre_save (look here) or post_save and put there the creation of BankAccount.

or you can actually save the TempUser with commit=False, crete the BankAccount and then save the TempUser

Upvotes: 0

Related Questions