Which part of Django API should I learn if I want to implement access control settings at a model-level?

I’m currently working on a project that involves mainly two models: 1. Collection model and 2. Item model.

For the Collection model, I want

  1. Collection name (string)
  2. Item list (an array of Item model)
  3. User list (an array of User model)

You can imagine the Collection model as a container of the Item model.

How can I implement this such that each user in a collection instance has a dedicated permission such as viewer, editor, and owner?

For example, how can I achieve something like this? And which part of Django API should I learn to do this?

{
  "collection_name": "My Collection",
  "item_list": [],
  "created_by": 3,
  "user_list": [
    { user_id: 1, role: "viewer" },
    { user_id: 2, role: "editor" },
    { user_id: 3, role: "owner" }
  ]
}

So the first thing you want to do is re-think your models in terms of a relational database.

What this (in general) is going to look like:

Model Collection
    collection_name
    created_by
    users = ManyToMany(User, through=UserCollection)

Model Item
    collection = ForeignKey(Collection)
        Note: This is assuming each item only belongs to one collection.
        If an individual item can belong to multiple collections, then it's a 
        ManyToMany relationship

Model UserCollection
    collection = ForeignKey(Collection, ...)
    user = ForeignKey(User, ...)
    role

Then, for each view, you will implement a security check for that view to ensure than the person making the request has the necessary permissions for that view.
See Using the Django authentication system | Django documentation | Django (The whole page - there’s a lot of information in there.)

1 Like