unknown
unknown

Reputation: 321

How to make a reverse relate between two models in one application?

How to make a reverse relate between two models in one application?

class User(AbstractUser):
    user_status = models.ForeignKey(Status)


class Status(models.Model):
    users = models.ManyToManyField(User, blank=True)

Upvotes: 0

Views: 49

Answers (2)

dirkgroten
dirkgroten

Reputation: 20672

Django does it automatically for you. So you should not specify it as a field on the related model.

Remove the ManyToManyField on Status. Then, if you have a Status object, you can reference the reverse relationship with status.user_set.all(). Or, you can add a related_name to the ForeignKey, you can use a custom name:

user_status = models.ForeignKey(Status, related_name="users", on_delete=models.SET_NULL, null=True, blank=True)

Note that I added on_delete since that's required in Django 2.x forces you to specify what should happen if the Status is deleted.

status = Status.objects.first()
status.users.all()  # all users for that status

Upvotes: 2

grouchoboy
grouchoboy

Reputation: 1024

You can access the statuses for a user with status_set:

user = User.objects.first()
user.status_set.all() # get all status of a user

You can assign another name to the reverse with the related_name argument:

class Status(models.Model):
    users = models.ManyToManyField(User, blank=True, related_name='states')


user = User.objects.first()
user.states.all()

Many to many official documentation

Upvotes: 0

Related Questions