Django Model: how to find list of auto-generated fields - django

Is there any Django built-in function that return a list of all auto-generated fields from a Django model?
Something like: MyModel._meta._get_auto_generated_fields()

You can filter the fields with list comprehension on the .auto_generated attributeĀ [Django-doc]:
[field for field in MyModel._meta.get_fields() if field.auto_created]

Related

DRF regex search on all fields

I need DRF '$'- regex search on all("__all__") fields of a model in Django Rest API Framework.
I can specify like search_fields = ['$username', '$first_name', '$email', '$last_name'] this on all fields explicitly on a model.
but I need $-regex search on all fields of a model something like search_fields = '$__all__'.
Please anybody giude me on this , Thanks in advance.
If you want a list of all the fields in a model, you can use
[field.name for field in model._meta.get_fields()]
You can add checks while building up the list of the fields:
[field.name for field in model._meta.get_fields() if field.name.startswith("$")]

How to replace foreign key by its associated value in django queryset

I'm fairly new to django and i would need your help!
I wrote an api/route view that query the database and return a JSON to my fetch function in my javascript.
Is there a way to query the database and got back a queryset with foreign key replaced by its associated value ?
I though i could use ModelName.objects.select_related( 'field ') but i didn't understand how it works.
If you have a solution or advices on better way to achieve the goal, Thanks in advance!
Context in pseudo-code:
// HTML //
Button onclick function get_list_of_data
// JS //
function get_list_of_data:
Fetch URL of route django
Convert response to JSON
iterating through JSON to fill HTLM div
// Django //
use ModelName.objects.filter( name = name ) to get list of data in Queryset
use serializers.serialize(json, ...") to get JSON from Queryset
return JsonResponse (json_query)
If I understood the problem well, when you serialize a model that has a ForeignKey field defined you get only the id value in JSON response but you would like to get the whole object (not only a number) returned.
The way to do that is to specifically write serializer for that ForeignKey model and then use it within the serializer od the model that you are trying to fetch.
You haven't provided any code, but here is some example that might help you:
class SecondModelSerializer(serializers.ModelSerializer):
class Meta:
model = SecondModel
fields = '__all__'
class FirstModelSerializer(serializers.ModelSerializer):
foreign_key_field = SecondModelSerializer()
class Meta:
model = FirstModel
fields = ('id', 'foreign_key_field', 'field1', 'field2')
Here in your FirstModelSerializer you specifically told Django to use SecondModelSerializer for your ForeignKey field (I named it foreign_key_field). This way Django will know how to serialize that field instead of returning only the id value.

Django get the Model name using ORM's related field name

I have a string like this order__product__category__description which is a related expression of my Django's model structure
Now I have a model called Shipment
field = 'order__product__category__description'
Here description is a column name of table/model Category. Here comes the question, just by having this model Shipment and this field string order__product__category__description how do I find these models Order, Product, Category.
My use-case is I need to store all the field_names of Category in a list. Any idea on how to connect the dots? having left with just two details Shipment & that field string.
First thing comes to mind is to split by __ and to come up with a list like this ['order','product','category'] and to iterate the model _meta based on the field name. Any other elegant ways would be appreciated.
If you want to get the related model from the model class (rather than the related instance from a model instance), you can use _meta.get_field() combined with field.related_model to get the related model class:
from django.core.exceptions import FieldDoesNotExist
model = Shipment
lookup = 'order__product__category__description'
for name in lookup.split('__'):
try:
field = model._meta.get_field(name)
except FieldDoesNotExist:
# name is probably a lookup or transform such as __contains
break
if hasattr(field, 'related_model'):
# field is a relation
model = field.related_model
else:
# field is not a relation, any name that follows is
# probably a lookup or transform
break
Then do with model what you want.
I didn't understand well. Anyway hope this you want.
field = 'order__product__category__description'
To get product from Shipment instance
product_var = ".".join(field.split("__")[:2])
Then
from operator import attrgetter
attrgetter(product_var)(shipment_instance)
Also you can get all related as a tuple
attrgetter(".".join(field.split("__")[:1]), ".".join(field.split("__")[:2]), ".".join(field.split("__")[:3]), ".".join(field.split("__")[:4]))(shipment_instance)
Hope this helps.
Assuming you have split the string it into a list, as you said to these:
models = ['order', 'product', 'category']
First get the app label (a string) that each model refers to:
from django.contrib.contenttypes.models import ContentType
app_labels = []
for model in models:
app_labels.append(ContentType.objects.filter(model=model).values('app_label').first().get('app_label'))
Now you have both model names and app names. So:
from django.apps import apps
model_classes = []
for app, model in zip(app_labels, models):
model_classes.append(apps.get_model(app, model))
Finally, get each model fields with the _meta attribute like you already know:
for model in model_classes:
print(model._meta.get_fields())

django how to return a list of entries from just one field

I have a model, Designs. This contains several fields, one of which is a datetime field, date_submitted.
How can I return a list of just the datetime fields from a list of objects? For instance, I have:
design_list = Design.objects.all().order_by('-date_submitted')[:10]
But this contains all the fields. How can I isolate just the date_submitted fields into a list?
Have a look at values_list for QuerySets:
[design.date_submitted for design in Design.objects.all().order_by('-date_submitted')]
Use values_list.
design_list = Design.objects.all().order_by('-date_submitted')[:10].values_list('design_list')
More on Django documentation

How do I set a field named by a string?

For a view that updates a model, I'd like to do something like this:
for field in ('name', 'parent', 'notes'):
if request.POST[field]:
myModel[field] = request.POST.get(field, '')
However, model's fields are accessed as properties (myModel.field), not dictionary items, and as far as I can tell there aren't get/set methods in Django models. Is there another way I can update these properties iteratively?
setattr()