Home > database >  Django Model for associating Favourites
Django Model for associating Favourites

Time:04-17

Use case: Want to let an admin create favourite relationships between users. To do this, I am creating a model called Favourites.

class Favourite(models.Model):
    user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE)
    otheruser = models.IntegerField()

However, both user and otherusers are both objects in CustomUsers. In the admin console, when adding a favourite I get a list of users, but I do not get a list of other users obviously.

What model field can I use so that when adding a favourite I get a list of users, and when choosing the otheruser that is also a list of users?

CodePudding user response:

It makes more sense here to add a ManyToManyField [Django-doc] in your CustomUser, so:

class CustomUser(models.Model):
    # …
    favorites = models.ManyToManyField(
        'self',
        symmetrical=False,
        related_name='fans'
    )
  • Related