How to work around lack of support for foreign keys across databases in Django

后端 未结 9 1382
生来不讨喜
生来不讨喜 2020-12-07 09:59

I know Django does not support foreign keys across multiple databases (originally Django 1.3 docs)

But I\'m looking for a workaround.

What doesn\'t work

9条回答
  •  离开以前
    2020-12-07 10:20

    Inspired by @Frans ' comment. My workaround is to do this in business layer. In the example given this question. I would set fruit to an IntegerField on Article, as "not to do integrity check in data layer".

    class Fruit(models.Model):
        name = models.CharField()
    
    class Article(models.Model):
        fruit = models.IntegerField()
        intro = models.TextField()
    

    Then honor reference relation in application code (business layer). Take Django admin for example, in order to display fruit as a choice in Article's add page, you populate a list of choices for fruit manually.

    # admin.py in App article
    class ArticleAdmin(admin.ModelAdmin):
        class ArticleForm(forms.ModelForm):
            fields = ['fruit', 'intro']
    
            # populate choices for fruit
            choices = [(obj.id, obj.name) for obj in Fruit.objects.all()]
            widgets = {
                'fruit': forms.Select(choices=choices)}
    
        form = ArticleForm
        list_diaplay = ['fruit', 'intro']
    

    Of course you may need to take care of form field validation (integrity check).

提交回复
热议问题