Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make a relation between a local and remote Model #21

Open
fxdgear opened this issue Nov 4, 2014 · 1 comment
Open

How to make a relation between a local and remote Model #21

fxdgear opened this issue Nov 4, 2014 · 1 comment

Comments

@fxdgear
Copy link

fxdgear commented Nov 4, 2014

In your DRF example you have frontend and backend apps.

In each, you are defining the models for "Articles" "Tags" etc...

But if for example there was a model in the front end, and you wanted to create a relationship to the "backend" between the two, how would you handle this?

@JocelynDelalande
Copy link
Contributor

@fxdgear You can use a custom ForeignKeyField class.

Eg:

class CrossDbForeignKey(models.ForeignKey):
    def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(models.ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        # Here is the trick, get db relating to fk, not to root model
        using = router.db_for_read(self.rel.to, instance=model_instance)

        qs = self.rel.to._default_manager.using(using).filter(
                **{self.rel.field_name: value}
             )
        qs = qs.complex_filter(self.rel.limit_choices_to)
        if not qs.exists():
            raise exceptions.ValidationError(self.error_messages['invalid'] % {
                'model': self.rel.to._meta.verbose_name, 'pk': value})

It can be used like:

class Membership(models.Model):
    member = CrossDbForeignKey(LdapUser)

I originally wrote this code to reference LDAP models from regular (db) model. More details in this article (in french, sorry).

But you have to be careful, you loose referential integrity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants