0

I'd like to make a OneToMany-relationship between one of my models and the builtin Permission model of django.contrib.auth.models.

My plan is to create at least one new permission when my model is created and delete this/these permissions when the model is deleted.

When it comes to Many-to-one relations the documentation recommends using a ForeignKey (https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/). But if I get this right, I would need (theoretically) to add a ForeignKey to the Permission model.

Am I on the wrong way? What would be the best practice to implement this?

1 Answers1

1

Django provides ManytoOne relationship through ForeignKey, which specifies a dual way relationship, however it needs to be specified in on of the models only. Intuitively if your model should be related to various Permission models, in the latter your need to specify rel = models.ForeignKey(YourModelClassName).

In this case you tell django that many instances of Permission can be related to a single YourModel instance.

Hope this helps.

tigrank
  • 31
  • 2
  • But with this method I would have linked ONE of my own models to ONE Permission. So the linkage would look like my_model -> Permission. I think I don't get it – Matthias Gilch Jun 06 '17 at 14:36
  • With this code you would have linked ONE of your models to MANY of the objects of class, where you wrote the rel =... code. The link below might be helpful for this case. Documentation of ForeignKey() also states ManytoOne relationship. https://docs.djangoproject.com/en/1.11/intro/tutorial02/ – tigrank Jun 06 '17 at 18:01
  • you have the reverse relation with "permission__yourobject_set.all()". See [the docs](https://docs.djangoproject.com/en/1.11/topics/db/queries/#following-relationships-backward) – allo Jun 06 '17 at 21:31