简体   繁体   English

从Django模型中的多对多关系中获取字段值

[英]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. 模型CategoryProfile模型有manytomany关系。

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 如果将类别ID 1分配给用户ID 2我想显示模块名称X

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 我尝试使用module_name = Coupling.objects.values('module_name')但这将返回所有module_names而不是与用户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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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