简体   繁体   English

如何按名称获取外键表字段

[英]how to get foreign key table field by name

throught this i am getting all the data fro the database通过这个,我从数据库中获取所有数据

context['table1'] = table1.objects.filter(user_id = hos_id).filter(type = 1).filter(status = 1)

Models I have我有的模型

class table2(models.Model):
    name = models.CharField(max_length=50,unique=True)
    STATUS_CHOICES = (
        (1, 'Active'),
        (0, 'Inactive'),
        (2, 'Deleted'),
    )
    status = models.IntegerField(
        _('status'), choices=STATUS_CHOICES, default=1)



class table1(models.Model):
    uid = models.IntegerField()
    vc = models.ForeignKey(table2, on_delete=models.CASCADE)
    v_no = models.CharField(max_length=25,unique=True)
    dist = models.CharField(max_length=11,blank=False,null=False)
    STATUS_CHOICES = (
        (1, 'user1'),
        (2, 'user2'),

Through above query i am getting multiple records every record have their vc which i am getting the primary key of vc i want the category name for the every record isntead of id relation of model is already given.通过上面的查询,我得到了多条记录,每条记录都有它们的 vc,我得到了 vc 的主键,我想要每条记录的类别名称,而不是模型的 id 关系。

please help me related to this i am facing this.请帮我解决这个问题,我正面临这个问题。 how can i get thename fromthe single query with data我如何从带有数据的单个查询中获取名称

Vehicle_list = Vehicle.objects.filter(user_id = hospital_id).filter(user_type = 
1).filter(status = 1)

context = {}
for item in Vehicle_list:
    context[item.user_id] = item.vehicle_category.category_name

add a str function to vehicle model向车辆模型添加 str 函数

def __str__(self):
        return self.vehicle_category.category_name

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

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