Home > front end >  What should I do so that the result of filter() function is the dictionary mapping result
What should I do so that the result of filter() function is the dictionary mapping result

Time:01-28

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'}

How do I get the function 'BNetworkEdge.objects.all()' is directly the dictionary mapping result?

Thanks!

CodePudding user response:

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}]

CodePudding user response:

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)
    
    
  •  Tags:  
  • Related