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

通过这个,我从数据库中获取所有数据


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

我有的型号


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'),

通过上面的查询,我得到了多条记录,每条记录都有它们的 vc,我得到了 vc 的主键,我希望每条记录的类别名称而不是模型的 id 关系已经给出。


请帮助我与此相关,我正面临这个问题。如何从带有数据的单个查询中获取名称


阿波罗的战车
浏览 132回答 2
2回答

一只斗牛犬

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

幕布斯7119047

向车辆模型添加 str 函数def __str__(self):        return self.vehicle_category.category_name
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python