I have Parent-Children Relation Table in Model which is as follows:
models.py
class ProductCategory(models.Model):
parent = models.ForeignKey(to='ProductCategory', blank=True, null=True, related_name="sub_cats", on_delete=models.CASCADE)
name = models.CharField(max_length=30, blank=False, null=False)
desc = models.TextField(blank=True, null=True, db_column='description')
def __str__(self):
return self.name
Data in table
Using this data I want to make a tree in react component where a user see how many types of categories a product has.
right now getting this
[
{
"id": 1,
"parent": null,
"name": "Electronics",
"desc": "All kinds of electronics items comes in this category",
"sub_cats": [
{
"id": 2,
"parent": 1,
"name": "Mobiles",
"desc": "Category for Smartphones, Features-Phone, etc.",
"sub_cats": [3]
}
]
},
{
"id": 2,
"parent": 1,
"name": "Mobiles",
"desc": "Category for Smartphones, Features-Phone, etc.",
"sub_cats": [
{
"id": 3,
"parent": 2,
"name": "X-Mobile",
"desc": "All Smartphones of X-Mobile",
"sub_cats": []
}
]
},
{
"id": 3,
"parent": 2,
"name": "X-Mobile",
"desc": "All Smartphones of X-Mobile",
"sub_cats": []
}
]
or any other idea for making tree
Related
We have the SecurityEventItem that have the owner taken from another security_location model and returned.
The logic behind not having security_location direct as a foreign key is that we get events with security_location names that are not added yet to database, but we want them to be registered without adding the missing security location to the database.
class SecurityEventItemGetSerializer(serializers.ModelSerializer):
epc = RfidTagNestedSerializer()
owner = serializers.SerializerMethodField('get_owner')
def get_owner(self, member):
location = SecurityLocationSerializer(models.SecurityLocation.objects.get(name=member.security_location)).data
owner_name = ProductOwnerSerializer(models.ProductOwner.objects.get(id=location["owner"])).data
return owner_name["owner_name"]
class Meta:
model = models.SecurityEventItem
fields = ["id", "epc", "acknowledged", "firstSeenTimestamp", "security_location", "owner"]
The ViewSet bellow
class SecurityEventItemGetViewset(viewsets.ModelViewSet):
"""SecurityEventItemGet Viewset
API endpoint that allows security event items to be viewed.
Allowed actions:
"GET"
"""
queryset = models.SecurityEventItem.objects.all()
serializer_class = serializers.SecurityEventItemGetSerializer
http_method_names = ['get']
filter_backends = [DjangoFilterBackend]
search_fields = ["owner"]
filterset_fields = {
'acknowledged': ['exact'],
'epc': ['exact', "in"],
'security_location': ['exact', "in"],
'firstSeenTimestamp': ['gte', 'lte'],
}
I have tryed SearchFilter unsuccesfull as simillar to DjangoFilterBackend it does not recognize the owner field added that does not belong to the SecurityEventItem model.
The response is like this: and I would like to make a filter on the request passing a parameter "owner" added to the existing ones.
[
{
"id": 73,
"epc": {
"id": 8371,
"number": "1234",
"product": {
"id": 1,
"name": "default_product",
"ean": "",
"description": "default product for foreign/unknown RFID tags",
"category": {
"id": 1,
"name": "default_category",
"description": "default category for foreign/unknown RFID tags"
},
"info": []
},
"state": 1,
"info": [],
"owner": {
"id": 1,
"owner_id": 1,
"owner_name": "George"
}
},
"acknowledged": false,
"firstSeenTimestamp": "2022-02-21T09:44:08",
"security_location": "Test Location",
"owner": "Second Owner"
},
{
"id": 72,
"epc": {
"id": 105177,
"number": "303625D4580B2484000002CA",
"product": {
"id": 590,
"name": "A78R07",
"ean": "5940000792305",
"description": "Fata de perna 50x70",
"category": {
"id": 1,
"name": "default_category",
"description": "default category for foreign/unknown RFID tags"
},
"info": "{\"company\": \"HOTEL Nr1\"}"
},
"state": 1,
"info": [],
"owner": {
"id": 1,
"owner_id": 1,
"owner_name": "Regina"
}
},
"acknowledged": false,
"firstSeenTimestamp": "2022-02-21T09:31:16",
"security_location": "Front Desk",
"owner": "Second Company"
}
]
I would really appreciate if someone could teach me how to do that, there are plenty of information regarding model filtering, but no filters for the filters added to extra fields
SerializerMethodField is read-only.
This field is generated only at the time of serialization and does not exist in the database.
Filters work only with the database, but the owner field is not there.
I think you should annotate the queryset with the data you want (.annotate(owner=...), Subquery() ), then the filter can work because that field will be returned from the database.
I have a problem in repeated grid, I have a drop-down list where the users will choose what model they want.
Then I also have a JSON array which contains the model and other description of different cars.
How can I auto fill the appropriate JSON value to textField according to the chosen value in the drop-down list?
Like for example: The user chose the model Toyota, only the Toyota car model present in the JSON will be displayed at textField.
The form I've created is available at https://demo.orbeon.com/demo/fr/orbeon/builder/edit/3b1ebd5340007f245b34ccd468c36c188b376bd6. And here is the JSON:
{
"corppassUser": {
"corppassData": null,
"corppassEntity": {
"primaryActiviyDesc": "Marine insurance ",
"companyType": "A1",
"corppassPreviousNames": [],
"entityType": "LC",
"primaryActivityCode": "65121",
"businessExpiryDate": "",
"secondaryActivityCode": "93202",
"corppassShareholders": [
{
"allocation": 20000,
"personRef": {
"personName": "ANDY",
"nationality": "SG",
"id": 8,
"idno": "S6001111A"
},
"currency": "SGD",
"id": 3,
"entityRef": null,
"category": "1",
"shareType": "1"
},
{
"allocation": 10000,
"personRef": {
"personName": "TIMOTHY TAN",
"nationality": "SP",
"id": 6,
"idno": "S1112374E "
},
"currency": "SGD",
"id": 1,
"entityRef": null,
"category": "1",
"shareType": "1"
},
{
"allocation": 10000,
"personRef": {
"personName": "CLARISSA LIN",
"nationality": "SG",
"id": 7,
"idno": "S3212386E"
},
"currency": "SGD",
"id": 2,
"entityRef": null,
"category": "1",
"shareType": "1"
}
],
"uen": "T15LP0005A"
},
"id": 1
}
}
I have 2 tables
Category's ( id, name )
Sub_categories ( id, key, value, category_id )
I'm trying to get all Category's whose all sub_categories are deactivated ( means are soft-deleted )
let me explain more
i have sub_categories data like this
[
{
"id": 1,
"category_id": 1,
"key": "sub 1",
"value": "sub_1",
"deleted_at": null
},
{
"id": 2,
"category_id": 1,
"key": "sub 2",
"value": "1",
"deleted_at": null
},
{
"id": 4,
"category_id": 1,
"key": "sub 3",
"value": "1",
"deleted_at": "2019-07-09 06:06:01"
},
{
"id": 5,
"category_id": 2,
"key": "sub 1",
"value": "33",
"deleted_at": "2019-07-09 06:06:01"
},
{
"id": 6,
"category_id": 2,
"key": "sub 2",
"value": "33",
"deleted_at": "2019-07-09 06:06:01"
}
]
i want only category_id -> 2 ( where all sub_categories are softedeleted )
hear's category model code
public function subCategory() {
$this->makeVisible('deleted_at');
return $this->hasMany('App\SubCategory','category_id','id');
}
$categories = Categories::doesntHave('subCategory')->get();
you first have to define Relationship between Categorys and Sub_categories - https://laravel.com/docs/5.8/eloquent-relationships.
Then use query to get what you want https://laravel.com/docs/5.8/queries
Get IDs of categories with sub categories:
$categoryIdsWithSubCategories = SubCategory::get()->pluck('category_id')->toArray();
Get categories without sub categories:
$categoriesWithoutSubCategories = Category::whereNotIn('id', $categoryIdsWithSubCategories)->get();
I have a ProductDocument model in CosmosDB, which represents a Product. Within that model there is a subdocument contributors which holds who has contributed to the Product. Each contributor has a role.
Now I have been experimenting with a query that needs to:
Only select ProductDocument with a contributor.roleDescription of Author
Only select ProductDocument with a division of Pub 1
Only include contributors sub documents with a contributor.roleDescription of Author in the result set.
Now I'm struggling with:
Part 3 of select above. How do I accomplish this bit as my result set is including both contributor.roleDescription of Author AND Illustrator
Example Cosmos Model:
[
{
"id": "1",
"coverTitle": "A Title",
"pubPrice": 2.99,
"division" :"Pub 1",
"Availability": {
"code": "20",
"description": "Digital No Stock"
},
"contributors": [
{
"id": 1,
"firstName": "Brad",
"lastName": "Smith",
"roleDescription": "Author",
"roleCode": "A01"
},
{
"id": 2,
"firstName": "Steve",
"lastName": "Bradley",
"roleDescription": "Illustrator",
"roleCode": "A12"
}
]
},
{
"id": "2",
"coverTitle": "Another Title",
"division" :"Pub 2",
"pubPrice": 2.99,
"Availability": {
"code": "50",
"description": "In Stock"
},
"contributors": [
{
"id": 1,
"firstName": "Gareth Bradley",
"lastName": "Smith",
"roleDescription": "Author",
"roleCode": "A01"
}
]
}]
Here is my SQL which I have been playing around with in the Data Explorer:
SELECT VALUE p
FROM Products p
JOIN c IN p.contributors
WHERE c.roleDescription = 'Author'
AND p.division = 'Pub 1'
Here is my LINQ query from my service:
var query = client.CreateDocumentQuery<ProductDocument>(
UriFactory.CreateDocumentCollectionUri("BiblioAPI", "Products"),
new FeedOptions
{
MaxItemCount = -1,
EnableCrossPartitionQuery = true
}
)
.SelectMany(product => product.Contributors
.Where(contributor => contributor.RoleDescription == "Author")
.Select(c => product)
.Where(p => product.Division == "Pub 1"))
.AsDocumentQuery();
List<ProductDocument> results = new List<ProductDocument>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<ProductDocument>());
}
It selects the correct records, but how do I de-select the Illustrator sub document of contributor, because at the moment I get the following:
{
"id": "1",
"coverTitle": "A Title",
"pubPrice": 2.99,
"division" :"Pub 1",
"Availability": {
"code": "20",
"description": "Digital No Stock"
},
"contributors": [
{
"id": 1,
"firstName": "Brad",
"lastName": "Smith",
"roleDescription": "Author",
"roleCode": "A01"
},
{
"id": 2,
"firstName": "Steve",
"lastName": "Bradley",
"roleDescription": "Illustrator",
"roleCode": "A12"
}
]
}
But the following output is what I want, excluding the Illustrator contributor sub document:
{
"id": "1",
"coverTitle": "A Title",
"pubPrice": 2.99,
"division" :"Pub 1",
"Availability": {
"code": "20",
"description": "Digital No Stock"
},
"contributors": [
{
"id": 1,
"firstName": "Brad",
"lastName": "Smith",
"roleDescription": "Author",
"roleCode": "A01"
}
]
}
EDIT:
I would like to filter on Product if one of the subdocument contributor.roleDescription equals Author. So if the Product record doesn't include a Author contributor I don't want it
I want to include each contributor subdocument that equals Author. So if there are multiple Author contributor subdocuments for a Product, I want to include them, but exclude the Illustrator ones.
You could have a Collection of ProductDocuments.
Help on the fluent LINQ syntax would help greatly.
Azure CosmosDB now supports subqueries. Using subqueries, you could do this in two ways, with minor differences:
You could utilize the ARRAY expression with a subquery in your projection, filtering out contributors that you don’t want, and projecting all your other attributes. This query assumes that you need a select list of attributes to project apart from the array.
SELECT c.id, c.coverTitle, c.division, ARRAY(SELECT VALUE contributor from contributor in c.contributors WHERE contributor.roleDescription = "Author") contributors
FROM c
WHERE c.division="Pub 1"
This assumes that you need to filter on division "Pub 1" first followed by the subquery with the ARRAY expression.
Alternately, if you want the entire document along with the filtered contributors, you could do this:
SELECT c, ARRAY(SELECT VALUE contributor from contributor in c.contributors WHERE contributor.roleDescription = "Author") contributors
FROM c
WHERE c.division="Pub 1"
This will project the original document with a "Pub 1" division in the property labeled "c", along with a filtered contributor array separately in the property labeled "contributors". You could refer this contributor array for your filtered contributors and ignore the one in the document.
This will do what you want, but obviously if you have multiple contributors you want to show it might not do quite what you are after - it's hard to tell with your question if that is what you want exactly
SELECT p.id, p.coverTitle, p.pubPrice, p.division, p.Availability, c as contributors
FROM Products p
JOIN c IN p.contributors
WHERE c.roleDescription = 'Author'
AND p.division = 'Pub 1'
and the output is:
[
{
"id": "1",
"coverTitle": "A Title",
"pubPrice": 2.99,
"division": "Pub 1",
"Availability": {
"code": "20",
"description": "Digital No Stock"
},
"contributors": {
"id": 1,
"firstName": "Brad",
"lastName": "Smith",
"roleDescription": "Author",
"roleCode": "A01"
}
}
]
Note that contributors is not a list, it's a single value, so if multiple contributors match the filter, then you will get the same product returned multiple times.
I have three tables:
users
id
name
role_id
password
...
role_user
id
role_id
user_id
roles
id
name
slug
...
Now I want to get a user list with users.id,users.name,
roles.id. That's my code:
$query = User::with(['roles'=>function($q){
$q->lists('role_id');
}])->get(['id','name']);
the response like that
{
"id": "1",
"name": "aaaa",
"roles": []
},
{
"id": "2",
"name": "bbbb",
"roles": []
},
when i don't pass the array to get method,the response like that:
{
"id": 1,
"name": "aaaa",
"password": "xxxxxxx",
"created_at": "2015-05-07 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 1,
"role_id": 2
}
}
]
},
{
"id": 2,
"name": "bbbb",
"password": "xxxxxxx",
"created_at": "2015-05-05 14:15:00",
"roles": [
{
"role_id": 2,
"pivot": {
"user_id": 2,
"role_id": 2
}
}
]
},
But i do not want the password,created_at and pivot field. How to filter these?
To get relations you need to get the foreign keys. Try this
$query = User::with(['roles'=>function($q){
$q->get(['id', 'name', 'slug']);
}])->get(['id','name', 'role_id']);
As for the pivot table, can you post you roles relation in the user model?
Edit
Add this to your user model to hide the pivot properties
protected $hidden = ['pivot'];
You can add more fields to that property to remove them from all queries.