MrLine
MrLine

Reputation: 688

Django get_or_create returns False

I'm creating a population script, from an MysqlDatabase to Django Models.
Im looping through my receiving data from the Mysql and thats going good.

Now I have to write it to the Django Database...

mdl, succeeded = models.User.objects.get_or_create(
    name=name,
    password=password,
    email=email
)

I'm printing succeeded so I can see what the feedback is, but all it gives me is False

My Django Model User is edited so all fields can be blank and allows NULL or have a default

My Model User:

username = models.CharField(max_length=20, blank=True, null=True)
slug = models.SlugField(null=True, blank=True)
email = models.EmailField(unique=True, null=True)
name = models.CharField("First and last name", max_length=100)
uses_metric = models.BooleanField(default=True)
position = models.CharField("Position", max_length=70, blank=True, null=True,)
utility = models.ForeignKey(Utility, default=1, blank=True, null=True)
supplier = models.ForeignKey(Supplier, default=1, blank=True, null=True)
currency = models.ForeignKey(Currency, default=1)
phone = models.CharField("Direct phone number", max_length=40, blank=True,  default='+')
gets_notifications_on_reply = models.BooleanField("Receive notifications", default=False)
memberlist = models.BooleanField("Show member in memberslist", default=True)
registration_date = models.IntegerField(default=floor(time.time()), blank=True, null=True)
is_staff = models.BooleanField(
    _('staff status'),
    default=False,
    help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
    _('active'),
    default=True,
    help_text=_(
        'Designates whether this user should be treated as active. '
        'Deselect this instead of deleting accounts.'
    ),
)
USERNAME_FIELD = 'email'

Upvotes: 2

Views: 7089

Answers (1)

ingofreyer
ingofreyer

Reputation: 1164

Please check your database. This means that the User objects you are querying from there already exists. This might be due to the object already existing or alternatively your code not using the correct database. Since migrations, often use multiple databases this might be a problem as well.

According to the Django documentation, get_or_create() does not return an object and a status succeeded but instead a flag created, which indicates if this object has been newly created or already existed in the database. If it already existed, the created flag (succeeded in your code) is False.

If you want to make sure that the error is not due to objects already existing, take one data pair for which created is false and try to retrieve it using the model's get() method. If this throws a DoesNotExist error then something else is the problem. If it returns an object then that object already existed.

Upvotes: 5

Related Questions