19π
Does this need to create an actual dict? could you get by with only something that looked like a dict?
class DictModelAdaptor():
def __init__(self, model):
self.model = model
def __getitem__(self, key):
return self.model.objects.get(key=key)
def __setitem__(self, key, item):
pair = self.model()
pair.key = key
pair.value = item
pair.save()
def __contains__(self, key):
...
You could then wrap a model in this way:
modelDict = DictModelAdaptor(DictModel)
modelDict["name"] = "Bob Jones"
etcβ¦
217π
You can also rely on django code already written ;).
from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])
- [Django]-Django β view sql query without publishing migrations
- [Django]-How to get GET request values in Django?
- [Django]-Django index page best/most common practice
26π
You are looking for the Values member of QuerySet which allows you to get a list of dictionaries from your query
Returns a ValuesQuerySet β a QuerySet
that evaluates to a list of
dictionaries instead of model-instance
objects. Each of those dictionaries represents
an object, with the keys corresponding
to the attribute names of model
objects.
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
- [Django]-ValueError: Missing staticfiles manifest entry for 'favicon.ico'
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
- [Django]-Disable a method in a ViewSet, django-rest-framework
17π
You want the in_bulk
queryset method which, according to the docs:
Takes a list of field values (
id_list
) and thefield_name
for those values, and returns a dictionary mapping each value to an instance of the object with the given field value. Ifid_list
isnβt provided, all objects in the queryset are returned.field_name
must be a unique field, and it defaults to the primary key.
It takes a list of IDs, so youβll need to get that first via the values_list
method:
ids = MyModel.objects.values_list('id', flat=True)
ids_to_model_instances = MyModel.objects.in_bulk(ids)
# {1: <MyModel: 1>, 2: <MyModel: 2>, 3: <MyModel: 3>}
- [Django]-Querying django migrations table
- [Django]-What are the options for overriding Django's cascading delete behaviour?
- [Django]-How to make two django projects share the same database
14π
You can use the python
serializer:
from django.core import serializers
data = serializers.serialize('python', DictModel.objects.all())
- [Django]-How to run own daemon processes with Django?
- [Django]-Django multiple template inheritance β is this the right style?
- [Django]-Django testing model with ImageField
8π
use
dict(((m.key, m.value) for m in DictModel.objects.all())
As suggested by Tom Leys, we do not need to get whole object, we can get only those values we need e.g.
dict(((m['key'], m['value']) for m in DictModel.objects.values('key', 'value')))
and if you need all values, it is better to keep whole object in dict e.g.
dict(((m.key, m) for m in DictModel.objects.all())
- [Django]-Django Model Field Default Based Off Another Field in Same Model
- [Django]-How to get POST request values in Django?
- [Django]-Automated django receive hook on server: respond to collectstatic with "yes"
- [Django]-Django Aggregation β Expression contains mixed types. You must set output_field
- [Django]-Django-rest-framework returning 403 response on POST, PUT, DELETE despite AllowAny permissions
- [Django]-Django-allauth: Linking multiple social accounts to a single user
4π
Perhaps Iβm missing something, but Django objects have a __dict__
attribute which seems be what you want.
- [Django]-Error: No module named psycopg2.extensions
- [Django]-Can django's auth_user.username be varchar(75)? How could that be done?
- [Django]-What is actually assertEquals in Python?
2π
To get values of a models into dictionary, add below code at the place where u need that dictionary
from models import DictModel
activity_map = dict(Plan.objects.values_list('key', 'value'))
activity_map is a dictionary which contains required information .
- [Django]-CSRF Failed: CSRF token missing or incorrect
- [Django]-Django: guidelines for speeding up template rendering performance
- [Django]-What's the difference between staff, admin, superuser in django?
2π
user = mymodel.objects.all()
user.values()
You can also try
user.values_list() # getting as list
- [Django]-Django return file over HttpResponse β file is not served correctly
- [Django]-Django: How to manage development and production settings?
- [Django]-Trying to migrate in Django 1.9 β strange SQL error "django.db.utils.OperationalError: near ")": syntax error"
1π
Or were you trying to do something like:
def someview(req):
models = MyModel.objects.all()
toTuple = lambda field: (getattr(field, 'someatt'), getattr(field, 'someotheratt'))
data = dict(map(toTuple,models))
return render_to_response(template, data)
- [Django]-Fields.E304 Reverse accessor clashes in Django
- [Django]-How do I perform query filtering in django templates
- [Django]-How to use Django ImageField, and why use it at all?
1π
To get a map of all of the instances in a queryset into a single dictionary with a specified model field as the key, try doing this
from django.forms.models import model_to_dict
from myApp.models import myModel
allObjs = myModel.objects.all()
f = {} # initialise the output
key = 'key' # one of the fields from myModel
[f.update({x[key]: x}) for x in [model_to_dict(y) for y in allObjs]]
return f
- [Django]-How to use if/else condition on Django Templates?
- [Django]-Programmatically saving image to Django ImageField
- [Django]-How to test custom django-admin commands