[英]Django Queryset does not show foreign key value
Im getting some problems when i try to access a Foreign Key value through a Django querySet. 我在尝试通过Django querySet访问外键值时遇到一些问题。 My model is:
我的模型是:
class Server(models.Model):
server_id = models.AutoField(primary_key=True)
mnemonic = models.CharField(max_length=30, unique=True)
active = models.BooleanField(default=True)
server_status = models.ForeignKey(Status, default=4)
def __unicode__(self):
return unicode(self.mnemonic)
class Status(models.Model):
status_id = models.AutoField(primary_key=True)
status_code = models.CharField(max_length=100)
def __unicode__(self):
return unicode(self.status_code)
When i execute the next code all runs OK, and i can obtain the FK associated value. 当我执行下一个代码时,所有代码都运行正常,并且可以获得FK关联值。
>>> print servers.models.Server.objects.get(server_id=3).server_status
Unmanagmed - Reacheable
But when i execute a query set, i cannot get the foreign key associated value: 但是,当我执行查询集时,我无法获得与外键关联的值:
>>> servers.models.Server.objects.filter(server_id=3).values("server_status")
[{'server_status': 2L}]
Im using django 1.6.1. 我正在使用Django 1.6.1。
any idea how could get the FK value? 知道如何获得FK值吗?
You should modify the Server class to have a ForeignKey to Status: 您应该将Server类修改为具有Status的ForeignKey :
class Server(models.Model):
status = models.ForeignKey('Status')
# ...
I dont't see any foreign key defined in your models. 我看不到您的模型中定义的任何外键。
You need a relationship in your model Status 您需要在模型中建立关系
class Status(models.Model):
status_id = models.AutoField(primary_key=True)
status_code = models.CharField(max_length=100)
server = models.ForeignKey(Server,
verbose_name='Server',
help_text='Select Server',
on_delete=models.PROTECT)
def __unicode__(self):
return unicode(self.status_code)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.