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

Python 从Django模型中的多个关系中获取字段值,python,django,Python,Django,我正在尝试获取与另一个模型关联的字段值。模型Category与Profile模型有manytomy关系 类别 id category_name module_name 1 A X 2 B Y id profile_id category_id 1 2 1 profile\u类别 id category_name module_name 1 A X 2

我正在尝试获取与另一个模型关联的字段值。模型
Category
Profile
模型有
manytomy
关系

类别

id   category_name module_name
1    A             X
2    B             Y
id    profile_id    category_id
1     2             1
profile\u类别

id   category_name module_name
1    A             X
2    B             Y
id    profile_id    category_id
1     2             1
例如,如果类别id
1
分配给用户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 
我尝试了
module\u name=Coupling.objects.values('module\u name')
,但这将返回所有模块名称,而不是与用户id 2关联的名称

非常感谢您的帮助/建议。提前感谢。

试试这个:

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

print(user.profile.category.values('module_name'))
更新:

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

谢谢但是我得到一个错误--
AttributeError:“User”对象没有属性“profile”
谢谢Jahongir。不同的错误-
name错误:没有定义名称“Profile”
@PrithvirajMitra那么,您需要
导入您的型号
Profile