Querying for model based on file name - django

I've got a filename:
filename = 'myfile.txt'
I'd like to be able to query for it.
summernoteimages = UserFile.objects.filter(
Q(file__name=filename)
)
I'm getting the following error: Unsupported lookup 'name' for FileField or join on the field not permitted.

UserFile.objects.filter(
Q(file__endswith=filename))
Or
UserFile.objects.filter(
Q(file__icontains=filename))

Related

Get instance by file name for a file in ImageField

Django 3.1.6
class ResponsiveImage(models.Model):
responsive_image = models.ImageField(upload_to=_raster_img_upload_to)
I want to find an instance by the image file_name:
file_name = 'img/raster/0a8449e7-8e50-4c02-853e-59a25592770d/img_144_96_fallback_3x_4.fallback'
ResponsiveImage.objects.get(responsive_image__name=file_name)
But this gets an error:
{FieldError}Unsupported lookup 'name' for ImageField or join on the field not permitted.
Could you help me?
When an ImageField is saved the string for the relative path to the image is stored in the database for your ResponsiveImage object for the field responsive_image.
You should be able to just go
ResponsiveImage.objects.get(responsive_image=file_name)
To get a specific ResponsiveImage object (As long as it actually exists in the database).

`op_name` parameter for `graphene_django`

The django graphene documentation shows a test example like this:
class MyFancyTestCase(GraphQLTestCase):
def test_some_query(self):
response = self.query(
'''
query {
myModel {
id
name
}
}
''',
op_name='myModel'
)
content = json.loads(response.content)
# This validates the status code and if you get errors
self.assertResponseNoErrors(response)
# Add some more asserts if you like
...
They don't have any API documentation for what op_name is, and what we should set it as. I tried to set it to my query name, but get the error:
[{'message': 'Unknown operation named "myQuery".'}]
Operation name is only needed when there are multiple operations in the query string. You only have one operation so the default (None) is fine.
https://docs.graphene-python.org/en/latest/execution/execute/#operation-name
As per my comment:
If the query is a mutation or named query, you must supply the op_name. For annon queries ("{ ... }"), should be None (default)
I am not sure how to create a "named query" with django graphene, but apparently my query is NOT a named query. Leaving op_name as None got my query to work via my unit test.

Loopback 4: How to access table with underscore in name from loopback 4?

I am trying to get data from my data source using loopback 4. It is working fine if the table name is simple and does not contain any special character.
But if there is a table with some special character like Underscore it does not allow me to create a model for that and I am not able to access the data from that table.
I have a table named "my_data" that contains column:- id,first_name,last_name.
But when I use the command lb4 model and pass the model name as my_data it converts it to my-data. and later on, when I call the API it throws an error by saying that relation publi.mydata does not exist.
WARNING: relational database doesn't support {strict: false} mode. {strict: true} mode will be set for model MyData instead.
Unhandled error in GET /my_data?filter=%7B%0A%20%20%22fields%22%3A%20%7B%0A%20%20%20%20%22id%22%3A%20true%2C%0A%20%20%20%20%first_name%22%3A%20true%2C%0A%20%20%20%20%22additionalProp1%22%3A%20%7B%7D%0A%20%20%7D%0A%7D: 500 error: relation "public.mydata" does not exist
at Connection.parseE (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9)
at Socket.Readable.push (_stream_readable.js:214:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Is ther any way to get data from table named like this? If anyone know how to do this please let me know.
Use settings.table in the #model decorator:
#model({
settings: {
table: 'my_data',
},
})
Further reading
https://loopback.io/doc/en/lb4/Model.html#data-mapping-properties

django tables2 export to xlsx: How to set exported filename using FBV?

Django==1.11.7
django-tables2==1.10.0
tablib==0.11.2
Using function based views, how to set the exported filename?
The tables 2 documentation gives a solution for class based views, but is not clear on function based views:
http://django-tables2.readthedocs.io/en/latest/pages/export.html?highlight=function%20based%20views
It mentions an "export_name", but where does this need to be set?
Trying this:
def export_payment_list(request):
_table = PaymentTable4Export(Payment.objects.all().order_by('-payment_date'))
RequestConfig(request).configure(_table)
exporter = TableExport('xlsx', _table)
return exporter.response('table.{}'.format('xlsx'), filename='my_test')
... results in an error:
Exception Type: TypeError
Exception Value:
response() got multiple values for argument 'filename'
Thank you for your help
It looks like the first argument of response() is the filename.
If you want the filename to be my_test.xlsx, try:
return exporter.response(filename='my_test.xlsx')

django jsonfield querying on a value which is an array

I have this model:
class InventoryItem(models.Model):
size_range = JSONField(null=True) # JSONField in Django 1.9
I populated following data in it:
InventoryItem.objects.create(size_range={'size': ['S', 'M', 'L']})
But When I do following query:
InventoryItem.objects.filter(size_range__size__contains='S')
I get following error:
django.db.utils.DataError: invalid input syntax for type json
LINE 1: ..._inventoryitem"."size_range" -> 'size' #> 'S' LIMIT ...
^
DETAIL: Token "S" is invalid.
CONTEXT: JSON data, line 1: S
How do I perform the query correctly using .filter() method?
This is the SQL query above .filter() method generates:
'SELECT "app_name_inventoryitem"."id",
"app_name_inventoryitem"."size_range", FROM
"app_name_inventoryitem" WHERE
"app_name_inventoryitem"."size_range" -> \'size\' #> S'
How do I perform the query correctly using .filter() method? Thanks in advance.
As mentioned in the documentation that contains operator accepts any JSON rather than just a dictionary of strings.
https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#containment-and-key-operations
you can do like the following
InventoryItem.objects.filter(size_range__size__contains=['S'])
This will return the object and if you do something like the following
InventoryItem.objects.filter(size_range__size__contains=['K'])
It will return an empty queryset.
You can do the following also:
InventoryItem.objects.filter(size_range__size__contains=['S', 'M'])
This will return your the object as well.
I haven't used django in a while, but, could this be what you where looking for?
InventoryItem.objects.filter(size_range__size__contains=['S'])