[英]Get field values from manytomany relationship in Django model
我正在嘗試獲取與另一個模型關聯的字段值。 模型Category
與Profile
模型有manytomany
關系。
Category
id category_name module_name
1 A X
2 B Y
profile_category
id profile_id category_id
1 2 1
例如。 如果將類別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
我嘗試使用module_name = Coupling.objects.values('module_name')
但這將返回所有module_names而不是與用戶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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.