Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django fixtures and OneToOneField

Tags:

python

django

As stated here objects are created automatically for models with OneToOne relationship to other models. So if I have Model1 with O2O to Model2, and will create object of Model2 with pk=1, then object of Model1 with model2_id=1 will be created autmatically. Then, if Ill dump data from DB to json, I will have two records for these objects. And if I will try to load this data to DB with loaddata - it will fail, because object for Model2 will be created twice and it will cause unique index violation and IntegrityError.
Does anybody found sane solution for this?

p.s.
I use Django 1.3.7

like image 851
Gill Bates Avatar asked Aug 29 '13 22:08

Gill Bates


People also ask

What is a one-to-one field in Django?

Django OneToOneField - One-to-one relationships A OneToOneField is used when you want to create a One-to-one relations. In this article, we will go over the usecase for such a field and how it should be implemented. When to use a one-to-one relationship?

Is it possible to use softonetoonefield with Django profile models?

This field builds on Django’s built-in OneToOneField, but with a few modifications, it could work with SoftOneToOneField. Now, when I create my profile models, I can add that property to the User model without touching the User model [0].

Why does Django onetoonefield throw an objectdoesnotexist exception?

The Django OneToOneField raises exceptions if the related model doesn’t exist. In order to check whether or not the related model exists, you have to use hasattr. One problem is that when you access a related model that doesn’t exist yet, it will throw a ObjectDoesNotExist exception. Which makes sense, but is kind of hard to use.

When to use a onetoonefield in Salesforce?

A OneToOneField is used when you want to create a One-to-one relations. In this article, we will go over the usecase for such a field and how it should be implemented. When to use a one-to-one relationship? #


2 Answers

I did something similar, notwith JSON but with xml, and my django is 1.7, so maybe it does not work for you.

  1. You can use natural keys when you are referencing serialized objects. This will prevent mixing up items if the index is already used by an other objject.
  2. You can use dependencies to define the order of serialization (and therefore deserialization).

Maybe similar posts like this one are helpful as well.

like image 86
OBu Avatar answered Oct 28 '22 00:10

OBu


When you dump your data fixtures, make sure you use the --natural argument:

python manage.py dumpdata myapp --indent=4 --natural

https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-option---natural

It looks its being deprecated in 1.7 for --natural-foreign

like image 36
Adam Spence Avatar answered Oct 28 '22 02:10

Adam Spence