В настоящее время я работаю с django и могу выбрать JSON моей модели. Но один из ключей JSON содержит массив чисел, который мне нужно заменить массивом объектов этих чисел. Ниже приведен запрос для получения json модели Contexts
queryset = serializers.serialize("json", Contexts.objects.all())
Это то, что я получаю
[{"model": "app.contexts", "pk": 1, "fields": {"context_name": "tech-experts", "context_description": "this is for tech experts", "context_priority": "H", "users": [1, 3, 4]}}, {"model": "app.contexts", "pk": 2, "fields": {"context_name": "video-conf-issue", "context_description": "bla bla", "context_priority": "H", "users": [4, 5]}}, {"model": "app.contexts", "pk": 3, "fields": {"context_name": "video-conf-issue", "context_description": "bla bla", "context_priority": "L", "users": [3]}}, {"model": "app.contexts", "pk": 15, "fields": {"context_name": "Network debug", "context_description": "Group for debugging network issues", "context_priority": "L", "users": [2]}}]
Теперь меня интересуют только значения fields
. Так что я делаю это
result = [i.get('fields') for i in ast.literal_eval(queryset)]
Так что теперь я получаю это
[{'context_priority': 'H', 'context_name': 'tech-experts', 'context_description': 'this is for tech experts', 'users': [1, 3, 4]}, {'context_priority': 'H', 'context_name': 'video-conf-issue', 'context_description': 'bla bla', 'users': [4, 5]}, {'context_priority': 'L', 'context_name': 'video-conf-issue', 'context_description': 'bla bla', 'users': [3]}, {'context_priority': 'L', 'context_name': 'Network debug', 'context_description': 'Group for debugging network issues', 'users': [2]}]
Теперь, как вы видите, users
имеет массив, который содержит целые числа. В основном эти целые числа являются идентификаторами пользователей, и я хочу, чтобы пользовательские объекты этих идентификаторов.
Итак, мой User
объект модели для userId
1, это будет
User.objects.filter(userId=1)
Итак, чтобы добиться этого, я делаю следующую операцию
[i.update({"users":[].append(User.objects.filter(userId=j))}) for i in result for j in i.get("users")]
Но теперь я получаю результирующее значение для ключа users
как None
[{'context_description': 'this is for tech experts', 'users': None, 'context_priority': 'H', 'context_name': 'tech-experts'}, {'context_description': 'bla bla', 'users': None, 'context_priority': 'H', 'context_name': 'video-conf-issue'}, {'context_description': 'bla bla', 'users': None, 'context_priority': 'L', 'context_name': 'video-conf-issue'}, {'context_description': 'Group for debugging network issues', 'users': None, 'context_priority': 'L', 'context_name': 'Network debug'}]
Как мне этого добиться?
Добавлены модели Contexts
и User
ниже
class User(models.Model):
userId = models.PositiveIntegerField(null = False)
pic = models.ImageField(upload_to=getUserImagePath,null=True)
Email = models.EmailField(null = True)
class Contexts(models.Model):
context_name = models.CharField(max_length=50)
context_description = models.TextField()
context_priority = models.CharField(max_length=1)
users = models.ManyToManyField(User, related_name='context_users')