I have a django serializer as below,
class VideoSerializer(CustomSerializer):
class Meta:
model = apis_models.Video
fields = '__all__'
def to_representation(self, video):
data = super().to_representation(video)
return {
'ordering': {
'video': {
"label": "Order By",
"options": {
"Newest First": '-upload_date',
"Oldest First": 'upload_date',
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
'body': data,
}
Which prints the output as below.
The "ordering" key appears in each element.
I need it to be appear only once at top. I believe using to_representation would be the best way to do it since it is a constant value. But I am not sure how do I get it only once.
How could I get it? Please help.
{
"count": 339,
"next": "http://10.0.0.238:8000/videos/?page=2",
"previous": null,
"results": [
{
"ordering": {
"video": {
"label": "Order By",
"options": {
"Newest First": "-upload_date",
"Oldest First": "upload_date",
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
"body": {
"id": 6142,
"source": {
"id": 5,
"name": "kpopdeepfakes_net",
"domain": "https://kpopdeepfakes.net",
}
}
},
{
"ordering": {
"video": {
"label": "Order By",
"options": {
"Newest First": "-upload_date",
"Oldest First": "upload_date",
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
"body": {
"id": 6153,
"source": {
"id": 5,
"name": "kpopdeepfakes_net",
"domain": "https://kpopdeepfakes.net",
}
}
},
I did it by adding below to my viewset.
def get_paginated_response(self, data):
return Response({
'ordering': {
'video': {
"label": "Order By",
"options": {
"Newest First": '-upload_date',
"Oldest First": 'upload_date',
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
'results': data
})
Related
I have inherited the following JSONField data structure:
[
{
"name": "Firstname",
"show": {
"value": true
},
"type": "text",
"uuid": "55668e45-07d1-404e-bf65-f6a3cacfaa97",
"label": {
"for": "Firstname",
"display": "First name"
},
"value": "Michael",
"options": [],
"required": true,
"component": "Input",
"placeholder": "Input text here",
"validationErrors": []
},
{
"name": "Surname",
"show": {
"value": true
},
"type": "text",
"uuid": "ce91fefa-66e3-4b08-8f1a-64d95771aa49",
"label": {
"for": "Surname",
"display": "Surname"
},
"value": "Roberts",
"options": [],
"required": true,
"component": "Input",
"placeholder": "Input text here",
"validationErrors": []
},
{
"name": "EmailAddress",
"show": {
"value": true
},
"type": "email",
"uuid": "6012a805-da62-4cee-8656-b7565b5f8756",
"label": {
"for": "Email",
"display": "Email"
},
"value": "michael#hiyield.co.uk",
"options": [],
"required": true,
"component": "Input",
"placeholder": "Input text here",
"validationErrors": []
},
{
"name": "University",
"show": {
"value": true
},
"type": "text",
"uuid": "434e3781-ab8a-4f09-9c68-5ec35188f3c7",
"label": {
"for": "University",
"display": "University/College"
},
"value": "University College London",
"options": [],
"required": true,
"component": "Input",
"placeholder": "Input text here",
"validationErrors": []
},
{
"name": "Subscribe",
"show": {
"value": true
},
"type": "checkbox",
"uuid": "79bdc29e-6357-4175-bf65-07be60776a29",
"label": {
"for": "Subscribe",
"display": "Subscribe to the KEVRI mailing list"
},
"value": true,
"options": [],
"required": true,
"component": "Checkbox",
"description": "KEVRI is committed to respecting and protecting your privacy. The data collected here will create your personalised report which we can email to you after this review if you wish. We will not share personal data with anyone else or send you any further emails.",
"placeholder": "",
"validationErrors": []
}
]
which exists on the models.JSONField called "about" for "MyModel", as follows:
class MyModel(
AbstractTimestampedModel
):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
about = models.JSONField()
I was wondering, how do I filter MyModel where the field within about is called by the "name": "EmailAddress" ... then query for that particular fields "value"?
Essentially, for the queryset MyModel.objects.all().filter() ... I want to filter out all the values where the EmailAddress is equal to some value ...
I'm not sure this is achievable within the Django ORM. However, there might be someone who could advise ...
If i am correct you should use jsonb_to_recordset PostgreSQL function.
Firstly you should create a custom database function since there is no function for that in Django Core.
class JSONRecordSet(Func):
template = "(SELECT id from %(function)s(%(expressions)s) as items(%(key)s %(output_type)s) where %(key)s='%(search)s')"
function = "jsonb_to_recordset"
def __init__(self, expression, key, output_type, search):
super().__init__(expression, key=key, output_type=output_type, search=search)
Please be aware of SQL injection.
After that, you can use this function with annotate.
MyModel.objects.annotate(_id=JSONRecordSet(expression="about", key="EmailAddress", output_type="text", search="foo#bar.com")).filter(id=F("_id"))
Return all MyModel instance which has "foo#bar.com" value in EmailAddress Key.
Try this approach:
MyModel.objects.filter(about__name='EmailAddress')
It might return the result you want.
Also, have a look at this link. It also describes how to query into nested dictionary using JSONField:
https://docs.djangoproject.com/en/3.2/topics/db/queries/#key-index-and-path-transforms
A beginner django question...
Here's a JSON response...
"data": [
{
"type": "Subject",
"id": "0",
"attributes": {
"created": "2019-01-01T00:00:00Z",
"modified": "2019-01-01T00:00:00Z",
"subject_code": "A&H",
"subject_name": "AH",
"subject_short_name": "A & HUM"
},
"relationships": {
"organization": {
"data": {
"type": "Organization",
"id": "61"
}
},
"created_user": {
"data": null
},
"last_updated_user": {
"data": null
}
},
"links": {
"self": "http://localhost:8001/v1/subject_owner/0"
}
},
The above response is coming from a serializer
queryset = Subject.objects.all()
I have a query which is
http://localhost:8001/v1/subject_owner?owner_ids=62,63
So, how do we write a filtering condition for the owner_ids as a list? The response should have only the results where the owner_ids match organization_id. I have tried few:
queryset.filter(organization__in=[owner_id_list])
and
queryset.filter(organization=owner_id_list)
and obviously they don't work. Any help will be appreciated.
FYI, here's the model class...
class SubjectManager(models.Manager):
def get_by_natural_key(self, subject_code):
return self.get(subject_code=subject_code)
class Subject(get_subject_base_class(Organization)):
objects = SubjectManager()
def __str__(self):
return self.subject_code
def natural_key(self):
return (self.subject_code,)
You have to make something like that:
owner_id_list = [62, 63]
Subject.objects.filter(organization_id__in=owner_id_list)
In loopback, how could I remove the PK from the swagger json displayed.
This is the json displayed in my swagger:
{
"user_id": "string",
"order_type": "string",
"date": "2016-04-28",
"payload": {
"id": 0
},
"id": 0
}
image detail- Swagger
how could I remove the "id": 0 ?
This is my order.json :
{
"name": "Order",
"plural": "Orders",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"user_id": {
"type": "string",
"required": true
},
"order_type": {
"type": "string",
"required": true
},
"date": {
"type": "date",
"required": true
},
"payload": {
"type": "Payload",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
This is my order.js:
module.exports = (Order) => {
Order.create = function(body, cb) {
//
}
Order.remoteMethod('create', {
'http': {'path': '/'},
'accepts': [
{'arg': 'body', 'type': 'Order', 'required': true, 'http': { 'source': 'body' } }
]
});
};
Hidden property did the trick
{
"name": "Order",
"plural": "Orders",
"base": "Model",
"idInjection": false,
"options": {
"validateUpsert": true
},
"properties": {
...
},
"validations": [],
"relations": {},
"acls": [],
"methods": {},
"hidden": ["id"]
}
I have a contact db table and model. Employee model inherits from contact.
If i do GET employees/ it returns all the contacts.
How should I set up my employee.json if I want to return only the contacts with partnerId = 1?
{
"name": "employee",
"base": "contact",
"strict": false,
"idInjection": false,
"options": {
"validateUpsert": true,
"postgresql": {
"schema": "public",
"table": "contact"
}
},
"scope": {
"where": {
"partnerId": 1
}
},
//...
}
Debug says calling GET employees/ makes the following query:
SELECT "name", "position", "email", "password", "id" FROM "public"."contact" ORDER BY "id"
It does not seem that scope is added.
models/partner.json
{
"name": "partner",
// ...
"properties": {
"name": {
"type": "string",
"required": true
},
// ...
},
"validations": [],
"relations": {
"contacts": {
"type": "hasMany",
"model": "contact"
}
//...
},
"acls": [],
"methods": {}
}
Try using the where filter, either in the REST API
/employees?filter[where][partnerId]=1
or in your Employee.js
Employee.find({ where: {partnerId:1} });
https://docs.strongloop.com/display/APIC/Where+filter
In my view I'm trying to loop all pages and extract the name for each using the code below. But it does not appear to work.
How can I achieve this?
view.py
json_dict = json.loads(request.POST['site'])
for item in json_dict['pages']:
item.json_dict['name']
the JSON data
{
"someitem": "xaAX",
"pages": [
{
"id": "1364484811734",
"name": "Page Name",
"type": "basic",
"components": {
"img": "",
"text": ""
}
},
{
"id": "1364484812918",
"name": "Contact",
"type": "contact",
"components": {
"text": "Send us an email using the form below.",
"contact-form": {
"contact-name": "zzz",
"contact-email": "zz"
}
}
},
]
}
This should work:
json_dict = json.loads(request.POST['site'])
for item in json_dict['pages']:
print item['name']