简体   繁体   中英

Get field values from manytomany relationship in Django model

I am trying to get field values which is associated with another model. The model Category has a manytomany relationship with Profile model.

Category

id   category_name module_name
1    A             X
2    B             Y

profile_category

id    profile_id    category_id
1     2             1

For eg. I would like to display the module name X if category id 1 is assigned to the user id 2

models.py

class Category(models.Model):
    category_name = models.CharField(max_length=150, blank=False, null=True, default="", unique=True)
    module_name = models.TextField(blank=False, null=True)

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile')
    phone_number = PhoneNumberField( blank=True, null=True)
    organisation = models.CharField(max_length=30, blank=True)
    category = models.ManyToManyField(Category)
    # Get the list of module names 

I tried with module_name = Coupling.objects.values('module_name') but this is returning all the module_names not the names which are associated with user id 2

Any help/suggestion is highly appreciated. Thanks in advance.

Try this:

user = User.objects.get(id=2)

print(user.profile.category.values('module_name'))

Update:

print(Profile.objects.filter(user=2).values('category__module_name'))

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