简体   繁体   中英

Django many-to-many relationship doesn't return set object

I've the following User model

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=False, unique=True, max_length=255)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

Which has a ManyToMany relationship with a Room

class Room(Base):
    name = models.CharField(unique=True, max_length=255)
    room_type = models.CharField(max_length=50, null=True)
    users = models.ManyToManyField(User, related_name='users')

When I run the following query,

rooms = user.room_set.all()

I get this error,

AttributeError: 'User' object has no attribute 'room_set'

What am I doing wrong here?

It's just because you have changed the related_name to users

users = models.ManyToManyField(User, related_name='users')

Instead of rooms = user.room_set.all() try rooms = user.users.all() .

Note that it's more convenient to name the related_name with the plural of the class_name , so you would have:

class Room(models.Model)
    users = models.ManyToManyField(User, )

If you want to use the one of django classname_set ; Just remove related_name , so user.room_set.all will work

Try this

class Room(Model.models):
    user = models.ForignKey (User,ONCASCADE  = models.delete)
    name = models.CharField(unique=True, max_length=255)
    room_type = models.CharField(max_length=50, null=True)
    users = models.ManyToManyField(User, related_name='users')

You don't have user attribute in Room model !

Use this in room class :

 users= models.ManyToManyField(User)

Also see django doc examples .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM