FieldDoesNotExist on loading Fixture - django

I'm trying to load a fixture called initial_data.json:
[{"pk": 1, "model": "contenttypes.contenttype", "fields": {"model": "logentry", "name": "log entry", "app_label": "admin"}}, {"pk": 2, "model": "contenttypes.contenttype", "fields": {"model": "permission", "name": "permission", "app_label": "auth"}}, {"pk": 3, "model": "contenttypes.contenttype", "fields": {"model": "group", "name": "group", "app_label": "auth"}}, {"pk": 4, "model": "contenttypes.contenttype", "fields": {"model": "user", "name": "user", "app_label": "auth"}}, {"pk": 5, "model": "contenttypes.contenttype", "fields": {"model": "contenttype", "name": "content type", "app_label": "contenttypes"}}, {"pk": 6, "model": "contenttypes.contenttype", "fields": {"model": "session", "name": "session", "app_label": "sessions"}}, {"pk": 7, "model": "contenttypes.contenttype", "fields": {"model": "tweet", "name": "tweet", "app_label": "tweeter"}}, {"pk": "2pwa7lb5legwb02jw2h76f1e70j2jmo7", "model": "sessions.session", "fields": {"expire_date": "2014-09-14T00:20:41.773Z", "session_data": "OWQ4MmE3ZGRkZjliOWY3OTQ5OTdiMDIyYjE5ZWMwNmUwZTAyMThhMjp7Il9hdXRoX3VzZXJfYmFja2VuZCI6ImRqYW5nby5jb250cmliLmF1dGguYmFja2VuZHMuTW9kZWxCYWNrZW5kIiwiX2F1dGhfdXNlcl9pZCI6MX0="}}, {"pk": "ncl522f8kc6bf242chahmc2squtioirb", "model": "sessions.session", "fields": {"expire_date": "2014-09-14T01:19:42.407Z", "session_data": "NjY0NjliYjNkNDk0ODJhYWRjMDk5MjNjODA1NTAxYWIzZjg3ZGFkYzp7fQ=="}}, {"pk": 1, "model": "auth.permission", "fields": {"codename": "add_logentry", "name": "Can add log entry", "content_type": 1}}, {"pk": 2, "model": "auth.permission", "fields": {"codename": "change_logentry", "name": "Can change log entry", "content_type": 1}}, {"pk": 3, "model": "auth.permission", "fields": {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 1}}, {"pk": 4, "model": "auth.permission", "fields": {"codename": "add_permission", "name": "Can add permission", "content_type": 2}}, {"pk": 5, "model": "auth.permission", "fields": {"codename": "change_permission", "name": "Can change permission", "content_type": 2}}, {"pk": 6, "model": "auth.permission", "fields": {"codename": "delete_permission", "name": "Can delete permission", "content_type": 2}}, {"pk": 7, "model": "auth.permission", "fields": {"codename": "add_group", "name": "Can add group", "content_type": 3}}, {"pk": 8, "model": "auth.permission", "fields": {"codename": "change_group", "name": "Can change group", "content_type": 3}}, {"pk": 9, "model": "auth.permission", "fields": {"codename": "delete_group", "name": "Can delete group", "content_type": 3}}, {"pk": 10, "model": "auth.permission", "fields": {"codename": "add_user", "name": "Can add user", "content_type": 4}}, {"pk": 11, "model": "auth.permission", "fields": {"codename": "change_user", "name": "Can change user", "content_type": 4}}, {"pk": 12, "model": "auth.permission", "fields": {"codename": "delete_user", "name": "Can delete user", "content_type": 4}}, {"pk": 13, "model": "auth.permission", "fields": {"codename": "add_contenttype", "name": "Can add content type", "content_type": 5}}, {"pk": 14, "model": "auth.permission", "fields": {"codename": "change_contenttype", "name": "Can change content type", "content_type": 5}}, {"pk": 15, "model": "auth.permission", "fields": {"codename": "delete_contenttype", "name": "Can delete content type", "content_type": 5}}, {"pk": 16, "model": "auth.permission", "fields": {"codename": "add_session", "name": "Can add session", "content_type": 6}}, {"pk": 17, "model": "auth.permission", "fields": {"codename": "change_session", "name": "Can change session", "content_type": 6}}, {"pk": 18, "model": "auth.permission", "fields": {"codename": "delete_session", "name": "Can delete session", "content_type": 6}}, {"pk": 19, "model": "auth.permission", "fields": {"codename": "add_tweet", "name": "Can add tweet", "content_type": 7}}, {"pk": 20, "model": "auth.permission", "fields": {"codename": "change_tweet", "name": "Can change tweet", "content_type": 7}}, {"pk": 21, "model": "auth.permission", "fields": {"codename": "delete_tweet", "name": "Can delete tweet", "content_type": 7}}, {"pk": 1, "model": "auth.user", "fields": {"username": "nina", "first_name": "", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2014-08-31T00:20:41.771Z", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$12000$2LSBfxYO9fJJ$UT/BLyRLwBQIOUtOfA2aKkGw+xe44ZNYD2TWXqXoT3E=", "email": "", "date_joined": "2014-08-30T18:10:53.539Z"}}, {"pk": 2, "model": "auth.user", "fields": {"username": "admin", "first_name": "Admin", "last_name": "", "is_active": true, "is_superuser": true, "is_staff": true, "last_login": "2014-08-31T00:22:38Z", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$12000$6JY3bvlplRf0$Rm6rcK9M3LNuTw1uZ3B/Je7rq420UCaf2iwmY8pIv2U=", "email": "admin#admin.com", "date_joined": "2014-08-31T00:22:38Z"}}, {"pk": 3, "model": "auth.user", "fields": {"username": "bob", "first_name": "Bob", "last_name": "Bobman", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2014-08-31T00:23:06Z", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$12000$ehuPT7BoKVpF$VZTxDeaHtLG7jU4wQ1erlFciwMk7l8aCp9MIjSVa/NU=", "email": "bob#bob.com", "date_joined": "2014-08-31T00:23:06Z"}}, {"pk": 4, "model": "auth.user", "fields": {"username": "amy", "first_name": "Amy", "last_name": "Smith", "is_active": true, "is_superuser": false, "is_staff": false, "last_login": "2014-08-31T00:23:24Z", "groups": [], "user_permissions": [], "password": "pbkdf2_sha256$12000$Tv4vWeWICkfS$qcMP+xddceQZMVjHbdOhOsV6LKOQntKOkiaqdEzS2p8=", "email": "amy#smith.com", "date_joined": "2014-08-31T00:23:24Z"}}, {"pk": 1, "model": "tweeter.tweet", "fields": {"text": "I'm an Admin! ", "user": 2, "timestamp": "2014-08-30T18:51:04Z"}}, {"pk": 2, "model": "tweeter.tweet", "fields": {"text": "Bob is the coolest name EVAR", "user": 3, "timestamp": "2014-08-29T18:51:19Z"}}, {"pk": 3, "model": "tweeter.tweet", "fields": {"text": "I <3 Tweeter", "user": 4, "timestamp": "2014-08-30T15:52:09Z"}}, {"pk": 1, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:22:38.417Z", "object_repr": "Admin", "object_id": "2", "change_message": "", "user": 1, "content_type": 4}}, {"pk": 2, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T00:22:57.048Z", "object_repr": "Admin", "object_id": "2", "change_message": "Changed first_name, email, is_staff and is_superuser.", "user": 1, "content_type": 4}}, {"pk": 3, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:23:06.858Z", "object_repr": "Bob", "object_id": "3", "change_message": "", "user": 1, "content_type": 4}}, {"pk": 4, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T00:23:17.098Z", "object_repr": "Bob", "object_id": "3", "change_message": "Changed first_name, last_name and email.", "user": 1, "content_type": 4}}, {"pk": 5, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:23:24.481Z", "object_repr": "Amy", "object_id": "4", "change_message": "", "user": 1, "content_type": 4}}, {"pk": 6, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T00:23:35.860Z", "object_repr": "Amy", "object_id": "4", "change_message": "Changed first_name, last_name and email.", "user": 1, "content_type": 4}}, {"pk": 7, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:51:05.451Z", "object_repr": "I'm an Admin! ", "object_id": "1", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 8, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:51:26.097Z", "object_repr": "Bob is the coolest name EVAR", "object_id": "2", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 9, "model": "admin.logentry", "fields": {"action_flag": 1, "action_time": "2014-08-31T00:52:12.916Z", "object_repr": "I <3 Tweeter", "object_id": "3", "change_message": "", "user": 1, "content_type": 7}}, {"pk": 10, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T01:06:18.846Z", "object_repr": "admin", "object_id": "2", "change_message": "Changed username.", "user": 1, "content_type": 4}}, {"pk": 11, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T01:06:26.076Z", "object_repr": "bob", "object_id": "3", "change_message": "Changed username.", "user": 1, "content_type": 4}}, {"pk": 12, "model": "admin.logentry", "fields": {"action_flag": 2, "action_time": "2014-08-31T01:06:34.096Z", "object_repr": "amy", "object_id": "4", "change_message": "Changed username.", "user": 1, "content_type": 4}}]
But I get the following error when I'm running syncdb or using load data:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle
call_command("migrate", **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 364, in sync_apps
hide_empty=True,
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
self.loaddata(fixture_labels)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata
self.load_label(fixture_label)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 141, in load_label
for obj in objects:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/serializers/json.py", line 84, in Deserializer
six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/serializers/json.py", line 78, in Deserializer
for obj in PythonDeserializer(objects, **options):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/serializers/python.py", line 120, in Deserializer
field = Model._meta.get_field(field_name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/options.py", line 554, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/wrb473/Documents/workspace/angulardjango/tweeter/fixtures/initial_data.json': ContentType has no field named u'name'
Where is the problem with the fixture?

On this page: https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#django.contrib.contenttypes.models.ContentType
"Changed in Django 1.8:
Before Django 1.8, the name property was a real field on the ContentType model." -- implies that as of 1.8 it's not a real field. Are you using 1.8? And if you remove name from your ContentType fixtures does it work?

This is because ContentType.name is a property and not a Field.
An excerpt from ContentType model definition:
class ContentType(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(_('python model class name'), max_length=100)
objects = ContentTypeManager()
# ...
#property
def name(self):
# ...
The only fields defined on this model are app_label and model.
This means that code that serialized your objects has also included the property, whose value cannot be set when deserializing.
You can try removing anything that is not a model Field (in your case it is only name) from data on serialization.

Related

Filter nested list by map key

I have a list like given in bellow. I want to filter this data using "map" key.
[
{
"model": "map.mapreferencepoints",
"pk": 3,
"fields": {"map": 2, "referenceName": "RF1", "corX": 906, "corY": 377}},
{
"model": "map.mapreferencepoints",
"pk": 4,
"fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377}},
{
"model": "map.mapreferencepoints",
"pk": 5,
"fields": {"map": 2, "referenceName": "RF3", "corX": 1171, "corY": 377}}
]
I want to get data has only map = 1 like;
[
{
"model": "map.mapreferencepoints",
"pk": 4,
"fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377}
}
]
How can I filter data by map key in this way?
my_list = [
{
"model": "map.mapreferencepoints",
"pk": 3,
"fields": {"map": 2, "referenceName": "RF1", "corX": 906, "corY": 377}},
{
"model": "map.mapreferencepoints",
"pk": 4,
"fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377}},
{
"model": "map.mapreferencepoints",
"pk": 5,
"fields": {"map": 2, "referenceName": "RF3", "corX": 1171, "corY": 377}}
]
filtered_list = [i for i in my_list if i["fields"]["map"] == 1]

serialization is not work properly in lower levels- django-rest-framework

my Comment model is like below:
class Comment(models.Model):
user = models.ForeignKey(User)
content = models.TextField()
parent = models.ForeignKey('self', related_name='answers')
I want to serializer comment and all of its answers. So i've wrote this serializer:
class CommentSerializer(ModelSerializer):
user = UserSerializer(fields=('get_full_name',), allow_null=True)
class Meta:
model = Comment
fields = ['user', 'content', 'answers']
depth = 10
now when I serialize a comment by this serializer, it works properly just for level 1 of the comment. the answers object shows all the data, such as user's password! or it shows 'parent' while I didn't include parent to the fields of Meta class of the serializer.
the following is the output of this serializer:
{
"data": {
"pk": 15,
"user": null,
"name": "rwqerweqr",
"email": null,
"content": "A",
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"answers": [
{
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": 3,
"parent": 15
}
}
}
}
}
}
}
}
}
},
{
"id": 16,
"content": "D",
"name": "werwer",
"email": null,
"approved": false,
"created_at": "2019-04-01T18:37:46.981327+04:30",
"user": null,
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 15,
"content": "A",
"name": "rwqerweqr",
"email": null,
"approved": false,
"created_at": "2019-03-31T23:16:44.980338+04:30",
"user": null,
"parent": {
"id": 13,
"content": "C",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T21:27:29.152248+04:30",
"user": {
"id": 3,
"is_superuser": true,
"email": "email#gmail.com",
"phone": "+111111111111",
"password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
"first_name": "Alex",
"last_name": "Doe",
"created_at": "2019-03-26T21:16:53.818407+04:30",
"last_login": "2019-03-26T21:17:14.987512+04:30",
"is_active": true,
"is_staff": true,
"groups": [],
"user_permissions": []
},
"parent": {
"id": 14,
"content": "B",
"name": null,
"email": null,
"approved": false,
"created_at": "2019-03-31T23:08:13.374350+04:30",
"user": 3,
"parent": 15
}
}
}
}
}
}
}
}
}
}
]
}
}
as you see, in the answers object, it shows user's data completely, include of its hashed password or permissions.
or it shows parent field while it is not in the serializer at all!.
how to solve this problem?
thanks.
UPDATE
usecase: Comments B and D are answers of comment A. (b.parent == A)
As displayed in django-rest-framework docs:
The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
If you want to customize the way the serialization is done you'll need to define the field yourself.
You should serialize the answers field, in order to hide those informations. I would follow the approach of SerializerMethodField. I will write an example:
class CommentSerializer(ModelSerializer):
user = UserSerializer(fields=('get_full_name',), allow_null=True)
answers = serializers.SerializerMethodField()
class Meta:
model = Comment
fields = ['user', 'content', 'answers']
def get_answers(self, instance):
# Here you will create your custom serialization

Ember Serialize 'ID'

I'm making an API call in Ember and the API I'm hitting is returning some JSON with 'ID' capitalized, it seems Ember is looking for lowercase 'id.' Everything else should work, so how would I serialize just this one piece of JSON in this instance?
See JSON below.
{
"ID": 2,
"name": "Main Menu",
"slug": "main-menu",
"description": "",
"count": 4,
"items": [
{
"id": 11,
"order": 1,
"parent": 0,
"title": "Contact",
"url": "http://localhost:8888/contact/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 7,
"object": "page",
"object_slug": "contact",
"type": "post_type",
"type_label": "Page"
},
{
"id": 12,
"order": 2,
"parent": 0,
"title": "About",
"url": "http://localhost:8888/about/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 5,
"object": "page",
"object_slug": "about",
"type": "post_type",
"type_label": "Page",
"children": [
{
"id": 21,
"order": 3,
"parent": 12,
"title": "About Us – Sub",
"url": "http://localhost:8888/about/about-us-sub/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 9,
"object": "page",
"object_slug": "about-us-sub",
"type": "post_type",
"type_label": "Page"
}
]
},
{
"id": 13,
"order": 4,
"parent": 0,
"title": "Home",
"url": "http://localhost:8888/home/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 2,
"object": "page",
"object_slug": "home",
"type": "post_type",
"type_label": "Page"
}
],
"meta": {
"links": {
"collection": "http://localhost:8888/wp-json/wp/v2/menus/",
"self": "http://localhost:8888/wp-json/wp/v2/menus/2"
}
}
}
You can define primaryKey: 'ID' by creating model specific serializer. read more for info https://guides.emberjs.com/v2.13.0/models/customizing-serializers/#toc_ids

Ember Array Iteration

I'm getting my JSON in my model and rendering it fine on the template, however, I'd like to access this array (items) on my template. The goal here is to dynamically render these menu items in the nav bar.
My handlebars looks like this,
{{#each menus as |menu|}}
{{#each menu.items as |items|}}
{{items}}
{{/each}}
{{/each}}
And returns
[object Object] [object Object] [object Object]
Any ideas?
JSON below.
{
"ID": 2,
"name": "Main Menu",
"slug": "main-menu",
"description": "",
"count": 4,
"items": [
{
"id": 11,
"order": 1,
"parent": 0,
"title": "Contact",
"url": "http://localhost:8888/contact/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 7,
"object": "page",
"object_slug": "contact",
"type": "post_type",
"type_label": "Page"
},
{
"id": 12,
"order": 2,
"parent": 0,
"title": "About",
"url": "http://localhost:8888/about/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 5,
"object": "page",
"object_slug": "about",
"type": "post_type",
"type_label": "Page",
"children": [
{
"id": 21,
"order": 3,
"parent": 12,
"title": "About Us – Sub",
"url": "http://localhost:8888/about/about-us-sub/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 9,
"object": "page",
"object_slug": "about-us-sub",
"type": "post_type",
"type_label": "Page"
}
]
},
{
"id": 13,
"order": 4,
"parent": 0,
"title": "Home",
"url": "http://localhost:8888/home/",
"attr": "",
"target": "",
"classes": "",
"xfn": "",
"description": "",
"object_id": 2,
"object": "page",
"object_slug": "home",
"type": "post_type",
"type_label": "Page"
}
],
"meta": {
"links": {
"collection": "http://localhost:8888/wp-json/wp/v2/menus/",
"self": "http://localhost:8888/wp-json/wp/v2/menus/2"
}
}
}

Raw SQL -> Django ORM Code: Query that returns all blog posts with most recent approved comment for a specific user

I'm working on a simple blog system. Here is my models.py file:
from django.contrib.auth.models import User
from django.db import models
class Comment(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey('Post')
content = models.TextField()
approved = models.NullBooleanField()
class Meta:
ordering = ('-id',)
def __unicode__(self):
return u'Comment by %s' % self.user
class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
slug = models.CharField(max_length=50)
content = models.TextField()
class Meta:
ordering = ('title',)
def __unicode__(self):
return self.title
Here is some test data in a fixture which I've named testdata.json (the "some_author" user is a superuser and the password is "Stack Overflow"):
[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "some_author",
"first_name": "Some",
"last_name": "Author",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2014-07-02T20:18:49Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$12000$PTl1hfgcIGZy$/0w1jNMBuKi9zk11JXhoS5WrbMBUgMDkZAhEvNEelbs=",
"email": "some_author#example.com",
"date_joined": "2014-07-02T20:18:29Z"
}
},
{
"pk": 2,
"model": "auth.user",
"fields": {
"username": "some_reader",
"first_name": "Some",
"last_name": "Reader",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2014-07-02T20:21:10Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$12000$CtTGfFeOaRhd$oVR6zFSpK2qg1AZ4fgdBG/wt6Sr56dHsEIxFO99mHC8=",
"email": "some_reader#example.com",
"date_joined": "2014-07-02T20:21:10Z"
}
},
{
"pk": 3,
"model": "auth.user",
"fields": {
"username": "another_reader",
"first_name": "Another",
"last_name": "Reader",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2014-07-02T20:21:34Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$12000$ZPnmV7fVeie3$08H2vv3A8Py4E92+uVAIiEaeg8CAL5deTyNAZj1YJMs=",
"email": "another_reader#example.com",
"date_joined": "2014-07-02T20:21:34Z"
}
},
{
"pk": 1,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 1 on post 1: approved",
"post": 1,
"user": 2,
"approved": true
}
},
{
"pk": 2,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 1 on post 2: not approved",
"post": 2,
"user": 2,
"approved": false
}
},
{
"pk": 3,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 2 on post 3: approved",
"post": 3,
"user": 2,
"approved": true
}
},
{
"pk": 4,
"model": "blog.comment",
"fields": {
"content": "Comment 2 of 2 on post 3: not approved",
"post": 3,
"user": 2,
"approved": false
}
},
{
"pk": 5,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 2 on post 4: not approved",
"post": 4,
"user": 2,
"approved": false
}
},
{
"pk": 6,
"model": "blog.comment",
"fields": {
"content": "Comment 2 of 2 on post 4: approved",
"post": 4,
"user": 2,
"approved": true
}
},
{
"pk": 7,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 2 on post 5: approved",
"post": 5,
"user": 2,
"approved": true
}
},
{
"pk": 8,
"model": "blog.comment",
"fields": {
"content": "Comment 2 of 2 on post 5: approved",
"post": 5,
"user": 2,
"approved": true
}
},
{
"pk": 9,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 2 on post 6: not approved",
"post": 6,
"user": 2,
"approved": false
}
},
{
"pk": 10,
"model": "blog.comment",
"fields": {
"content": "Comment 2 of 2 on post 6: not approved",
"post": 6,
"user": 2,
"approved": false
}
},
{
"pk": 11,
"model": "blog.comment",
"fields": {
"content": "Comment 1 of 1 on post 7: approved",
"post": 7,
"user": 3,
"approved": true
}
},
{
"pk": 1,
"model": "blog.post",
"fields": {
"content": "First post",
"slug": "post-1",
"user": 1,
"title": "Post 1"
}
},
{
"pk": 2,
"model": "blog.post",
"fields": {
"content": "Second post",
"slug": "post-2",
"user": 1,
"title": "Post 2"
}
},
{
"pk": 3,
"model": "blog.post",
"fields": {
"content": "Third post",
"slug": "post-3",
"user": 1,
"title": "Post 3"
}
},
{
"pk": 4,
"model": "blog.post",
"fields": {
"content": "Fourth post",
"slug": "post-4",
"user": 1,
"title": "Post 4"
}
},
{
"pk": 5,
"model": "blog.post",
"fields": {
"content": "Fifth post",
"slug": "post-5",
"user": 1,
"title": "Post 5"
}
},
{
"pk": 6,
"model": "blog.post",
"fields": {
"content": "Sixth post",
"slug": "post-6",
"user": 1,
"title": "Post 6"
}
},
{
"pk": 7,
"model": "blog.post",
"fields": {
"content": "Seventh post",
"slug": "post-7",
"user": 1,
"title": "Post 7"
}
},
{
"pk": 8,
"model": "blog.post",
"fields": {
"content": "Eighth post",
"slug": "post-8",
"user": 1,
"title": "Post 8"
}
}
]
I'm trying to query the database for all of the blog posts along with each blog post's most recent comment that meets both of these two conditions:
The comment was made by "Some Reader" (user_id = 2)
The comment has been approved
I want the query to return all of the blog posts, even if they don't have a comment that meets the above two conditions. For the blog posts that don't have a comment that meets the above two conditions, the returned comment column should just be NULL. I have this working with raw SQL:
for p in Post.objects.raw(
'''
SELECT blog_post.id,
blog_post.title,
blog_comment.content
FROM blog_post
LEFT OUTER JOIN (SELECT post_id,
MAX(id) AS latest
FROM blog_comment
WHERE user_id = 2
AND approved = 1
GROUP BY post_id) AS x
ON x.post_id = blog_post.id
LEFT OUTER JOIN blog_comment
ON blog_comment.post_id = x.post_id
AND blog_comment.id = x.latest
ORDER BY blog_post.id;
'''
):
print '%s: %s' % (
p.title,
p.content,
)
The above code outputs this (which is what I want):
Post 1: Comment 1 of 1 on post 1: approved
Post 2: None
Post 3: Comment 1 of 2 on post 3: approved
Post 4: Comment 2 of 2 on post 4: approved
Post 5: Comment 2 of 2 on post 5: approved
Post 6: None
Post 7: None
Post 8: None
My question is this: is it possible to (efficiently) do this same thing, but without resorting to raw SQL? I like to avoid raw queries whenever possible.
You can't do it without raw sql inside django orm paradigm.
But you can do it with two queries to db:
from django.db.models import Max
posts = Post.objects.annotate(Max('comment_set__id'))
comments_cache = Comment.objects.filter(id__in= posts.values('id', flat=True))
comments_dict = dict([(item.id, item) for item in comments_cache])
for item in posts:
print post, comments_dict[item.id]
I often make complex queries and still can't find better way than get all data I need with few queries inside cache-object and than group it as I need.
Please don't use code like:
#get_comment: return self.comment_set.filter(user=user, approved=True).latest('id')
for post in Post.objects.all():
print post.get_comment(request.user)
It will produce len(posts) sql-queries to database. It's bad practice.
You want all posts, but comments should be the one that matches specified criteria otherwise None. For that you can add a method/property inPost` model to get recent comment the way you wanted.
Don't think there is good way of doing this with ORM.
Add following method in your model,
class Post(models.Model):
...
#your code
def get_comment(self, user):
comment = None
try:
comment = self.comment_set.filter(user=user, approved=True).latest('id')
except Comment.DoesNotExist:
comment = None #no comment matching criteria
return comment
From you view or other code, you can do
for post in Post.objects.all():
print post.get_comment(request.user)