I have a model like this:
class BNetworkEdge(models.Model):
id = models.AutoField(unique=True, primary_key=True)
source = models.IntegerField()
target = models.IntegerField()
edge_type = models.IntegerField()
class Meta:
managed = True
db_table = 'b_network_edge'
I have a dictionary like this:
{0:'direct', 1:'no-direct'}
I run this in python shell
>>> BNetworkEdge.objects.filter()[0].edge_type
0
How to get a result of 'direct' instead of '0'?
Thanks!
In order to get dictionary mapping result in your view, you will do something like this:
#Your models.py
class BNetworkEdgeManager(models.Manager):
def get_queryset(self):
# The return of query by manager
return list(super().get_queryset().values('id', 'data_dict'))
class BNetworkEdge(models.Model):
id = models.AutoField(unique=True, primary_key=True)
source = models.IntegerField()
target = models.IntegerField()
edge_type = models.IntegerField()
objects = BNetworkEdgeManager()
# This goes in views.py
from .models import BNetworkEdge
def bnetwork_edge_view(request):
# this context to holds your data as a dictionary
context = {}
dict_data = BNetworkEdge.objects.all()
context = {'dict_data':dict_data}
# You can print the content of your context variable
# to see the dictionary objects
print(context)
return render(request,"Put Your Html Template Here eg.('network.html/')",context)
You need to create model manager as,
from django.db import models
class BNetworkEdgeManager(models.Manager):
def get_queryset(self):
# write custom logic here
return list(super().get_queryset().values('id', 'source'))
class BNetworkEdge(models.Model):
id = models.AutoField(unique=True, primary_key=True)
source = models.IntegerField()
target = models.IntegerField()
edge_type = models.IntegerField()
objects = BNetworkEdgeManager()
class Meta:
managed = True
db_table = 'b_network_edge'
Then you can access it as,
In [2]: BNetworkEdge.objects.all()
Out[2]: [{'id': 1, 'source': 1}]
Add the choices as proper choices
on your field
class BNetworkEdge(models.Model):
class EdgeTypes(models.IntegerChoices):
DIRECT = 1, 'direct'
NO_DIRECT = 2, 'no-direct'
id = models.AutoField(unique=True, primary_key=True)
source = models.IntegerField()
target = models.IntegerField()
edge_type = models.IntegerField(choices=EdgeTypes.choices)
class Meta:
managed = True
db_table = 'b_network_edge'
You can then call get_edge_type_display
to get the choice label
BNetworkEdge.objects.filter()[0].get_edge_type_display()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.