It didn't occur to me that this could be done with transactions, but in 
retrospect it seems obvious. Thanks for the quick response.

On Tuesday, January 21, 2014 12:43:28 PM UTC, Russell Keith-Magee wrote:
>
>
> On Tue, Jan 21, 2014 at 6:54 PM, antialiasis <antia...@gmail.com<javascript:>
> > wrote:
>
>> Hi,
>>
>> I just bumped into this issue. Say I have the following models:
>>
>>
>> class Foo(models.Model):
>>     bar = models.ForeignKey('Bar', related_name='foos')
>>
>> class Bar(models.Model):
>>     default_foo = models.ForeignKey(Foo, related_name='+')
>>
>>
>> Basically, the idea is that each bar has many foos, but one of them is 
>> the bar's default foo. Every foo must have an associated bar, and each bar 
>> must have a default foo, so both of the ForeignKey fields are NOT NULL.
>>
>> This was working great until I realized that now I can't actually create 
>> any Foo or Bar objects, because I can't save a Foo object without setting 
>> its bar_id, and I can't save a Bar object without setting its foo_id.
>>
>> Does Django have any kind of way around this, or is the solution just to 
>> allow null for one of them (dangerous for data integrity)? Or should I 
>> perhaps just not use this kind of circular reference altogether and instead 
>> go with something like an is_default field on the Foo model?
>>
>
> This is what database transactions are for. A transaction is a way to make 
> a series of individual changes as a single atomic change in the database. 
>
> In Django 1.6, the main way to implement transactional behaviour is to use 
> the atomic decorator:
>
>
> https://docs.djangoproject.com/en/1.6/topics/db/transactions/#django.db.transaction.atomic
>
> The only place this doesn't work is with MySQL, because it has a broken 
> implementation of referential integrity. If you're using PostgreSQL (which 
> implements referential integrity at the transaction boundary) or SQLite 
> (which doesn't have referential integrity), a transaction will do the job.
>
> If you have to use MySQL (and personally, I'd really recommend you don't), 
> the approach you've described of making one of the fields nullable is what 
> you have to do.
>
> Yours,
> Russ Magee %-)
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/79b485d9-ceb8-45b0-8d99-67797559a0e0%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to