Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a subquery to get a COUNT from a different table in Django
I have these models: class IceCream(models.Model): name = models.CharField(max_length=255) class Topping(models.Model): name = models.CharField(max_length=255) ice_cream = models.ForeignKey(IceCream, on_delete=models.CASCADE, related_name="toppings") is_active = models.BooleanField(db_index=True) I would like to run the following query to get a list of all ice creams, together with a count of the total number of available toppings, which in SQL would look like this: SELECT ice_cream.*, (SELECT COUNT(id) FROM topping WHERE topping.ice_cream = ice_cream.id AND topping.is_active = True) AS total_toppings FROM ice_cream This is a simplified version and there are more parameters in there, but if I can make this work, then things should work out. Can I do this in Django using Subquery expressions? I have not managed to make it work. Or are raw queries my only way out here because of the COUNT that I want to include in the subquery? -
'bytes' object has no attribute 'items' while using list
Getting error in: items = [item for item in body.items()] I just want to add multiple orderitems. I don't know this loop will work after this error. But atleast you will understand my requirement I am giving following data: [ { "service_id": 1, "quantity": 2, "price": 20 }, { "service_id": 2, "quantity": 3, "price": 20 }, { "service_id": 3, "quantity": 4, "price": 20 } ] @api_view(['GET', 'POST']) @csrf_exempt # class CreteOrderView(View): def create_order(request, *args, **kwargs): if request.method == 'POST': now = datetime.date.today() order = Order.objects.create(date=now) order.save() orderid = order.id order_id = orderid data = json.loads(request.body) price = request.session.get('price') quantity = request.session.get('quantity') print('quantity ' + str(quantity)) service_id = request.session.get('service_id') body = request.body items = [item for item in body.items()] for item in items: orderitemcreate= OrderItem.objects.create(order_id_id=order_id, service_id_id=service_id, quantity=quantity, price=price) orderitemcreate.save() return Response({"Order_id":str(order.id), "Order_date":str(order.date), "OrderItems_id" :str(orderitemcreate.id), "service_id" :str(orderitemcreate.service_id), "quantity" :str(orderitemcreate.quantity), "price":str(orderitemcreate.price)}) else: order_qs = models.Order.objects.all().values_list() OrderItem_qs = models.OrderItem.objects.all().values_list() return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)}) -
is it possible to have google-auth within django template?
I have a django app that uses Google's allauth for signing up and logging in, but it first takes me to a google url and to sign in, i.e., my header and other parts of my site are not visible. Once I log in through my google account I'm redirected, so the logic works fine. I'm just wondering if it's possible to have that process be done on my site. -
Why is my DRF view accepting post requests without a csrf token in the headers?
I've just started using Django Rest Framework, and I'm slightly confused about the usage of CSRF tokens in requests. For example, using a standard Django view with the below request would require a CSRF token: fetch("http://127.0.0.1:8000/api/add_item/", { method: "POST", headers: { "Content-Type": "application/json" // "X-CSRFToken": Cookies.get("csrftoken") }, body: JSON.stringify({ content: value }) }) But doesn't seem to with the below DRF implementation: @api_view(['POST']) def add_item(request): serializer = ToDoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Is there a reason for this? -
Choice field model django
I have created a model called ingrident where I have store all the ingrident name now I want to pass all these items into choice of a field in another model. How can I do this I don't want to use foreign key because I want to Crete the choice field in inline formset so that the user can Crete recipe by selecting multiple ingrident and giving each ingrident with quantity -
Django Forms allow user to input a list of tuples of unknown length
The app I'm creating requires instances of lessons to be created. For each lesson, any number of instructors can be assigned each with a specific user-inputted role. For example: Lesson 1 has the following instructors role: head, name: Bob role: example, name: Adam role: assistant, name: Joy Because the roles are unknown and the amount of instructors are unknown, the form must be able to accept a list of 'tuples'. Each tuple would then need a textfield and a select field (selecting form a list of instructors). The data would then be saved in this model: class MapInstructorTeach(models.Model): teach = models.ForeignKey(Teach, on_delete=models.CASCADE) instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE) role = models.CharField(max_length=32) The Teach model is just a model specifying the name of the lesson. The instructor model is a list of instructors. How would I go about creating the forms.py class and the html for something like this? I don't even know where to begin. Attempts jQuery infinite input form I've tried using the above method to generate the fields in the front end but couldn't figure out a way to link the input fields to the backend. -
object has no attribute 'set_password'
I am getting an error message of 'UserProfileInfo' object has no attribute 'set_password' I cant seem to find what I missing I did a few projects alike this one but never encountered such error Is there something I missing. I have been trying to fix this for the past hour but still no luck I would appreciate it if you help me out from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import UserForm , LoginForm # Create your views here. def home(request): if not request.user.is_authenticated: message = "You are not logged in" return render(request,'home.html',{"MESSAGE":message}) else: message = "You are logged in" return render(request,'home.html',{"MESSAGE":message}) def Register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'signup.html', {'user_form': user_form,'registered':registered}) def user_login(request): if request.method == 'POST': login_info = LoginForm(request.POST) if login_info.is_valid(): user = authenticate(username = login_info.cleaned_data["username"], password=login_info.cleaned_data["password"]) if user: login(request,user) return HttpResponseRedirect(reverse('Home')) else: return HttpResponse("Wrong") else: login_info = LoginForm() return render(request,"login.html",{'logininfo':login_info}) My form from cProfile import label from re import L from django import forms from django.contrib.auth.models import User from .models import … -
Django - multiple forms on one view - passing uncreated object to second form
I wonder if it is possible to make two django model based forms on one view which one requires object which is gonna be created by second (Foreign Key). I will show an example to make it more understandable I got these models: class Recipe(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=200) quantity = models.CharField(max_length=200) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return self.name as you can see, Indgredient model takes Recipe as an parameter. I'd like to make a form, which allow user to make new Recipe and Ingredient (or ingredients) which recipe field will be filled by a recipe creating in the same view I was trying to make it this way from .models import Ingredient, Recipe from django.forms import ModelForm class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name'] def recipeAndIngredientsCreationView(request): form1 = RecipeForm() form2 = IngredientForm() if request.method == "POST": data1 = { 'csrfmiddlewaretoken': request.POST['csrfmiddlewaretoken'], 'name': request.POST['name'], } form1 = RecipeForm(data1) if form1.is_valid(): form1.save() print("recipe created") data2 = { 'csrfmiddlewaretoken': request.POST['csrfmiddlewaretoken'], 'name': request.POST['name'], 'quantity' : request.POST['quantity'], 'recipe_id': Recipe.objects.get(name=request.POST['name']).id, } form1 = IngredientForm(data2) if form2.is_valid(): form2.save() return redirect('home') context = {'form1':form1, … -
How to use JSON in Django functions
i'm doing a django project for adding and updating things with a mysql database, but i was told that it's not safe to add and update thing directly without JSON, is this possible? how can i do that? here's my create function: form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'tasks/room_form.html', context)``` -
Django custom model save() method, how do you pass a form non-persistent form value?
In Django 4 custom model save() method, how do you pass a form non-persistent form value? For example: The model form below has the non-persistent field called client_secret. class ClientModelForm(forms.ModelForm): client_secret = forms.CharField(initial=generate_urlsafe_uuid) This field will never be saved, it is auto-generated and will be required to make a hash for a persisted field in my model save() method. class Client(models.Model): client_hash = models.BinaryField(editable=False, blank=True, null=True) def save(self, *args, **kwargs): """ Save override to hash the client secret on creation. """ if self._state.adding: "GET THE CLIENT SECRET FROM THE FORM" client_hash = make_hash_key(client_secret) self.client_hash = client_hash How do I get the client secret value from the form above code example? Is this the most appropriate approach? -
My presave slugify function seems to have stopped working in localhost, but not on deployed version? Has this happened to anyone else?
I have been working on a dog adoption website which I have been builing on my local host in python using the Django framework. I have a python page which uses the pre-save function to create a unique slug for the dog whenever one is created. I have now deployed my website and this works absolutely fine. However, as of today this seems to have stopped working on my local host. I cannot find any reason why and it uses the same code as the deployed version of the system. Has anyone ever experience this before and if so does anyone have a solution as I would like to keep working and maintaining on my localhost. class Dogs(models.Model): dog_id = models.AutoField(primary_key=True) dog_name = models.CharField(max_length=100) dog_slug = models.SlugField(unique=True, null=True, blank=True) breed = models.ForeignKey(Dog_breed, on_delete=models.CASCADE) dogs_image = models.ImageField(upload_to='media/') description = models.TextField(default="Description information to be added soon") dog_illness_disability = models.BooleanField(null=True, blank=True) can_live_with_cats = models.BooleanField(null=True, blank=True) can_live_with_dogs = models.BooleanField(null=True, blank=True) can_be_with_children = models.BooleanField(null=True, blank=True) hours_excercise_required = models.IntegerField(default=0) dog_sociability = models.IntegerField(default=0) can_be_left_alone = models.IntegerField(default=0) weight_kg = models.FloatField(default=0) size_range = models.IntegerField(default=0) affection_level = models.IntegerField(default=0) training_level = models.IntegerField(default=0) energy_level = models.IntegerField(default=0) age = models.IntegerField(default=0) age_range = models.IntegerField(default=0) male_female = models.BooleanField(null=True, blank=True) neutered = models.BooleanField(null=True, blank=True) slugify.py: def … -
pip install mysql-connector-python-8.0.30 installed completely - no errors. What are confer for settings .py [DATABASES ]
Environment = macOS Monterey V12.5 M1Max with Visual Studio Code + Python 3.10.6 + Django 4.1 + PIP3. Have successfully installed mysql-connector-python-8.0.30. Current dbsqlite3 has populated tables. When I run python manage.py migrate from dbsqlite3 to MySQL Community 8.0.30 the error messages include "Did you install mysqlclient." Oracle documentation indicates the mysql-connector-python should be used and is all that is needed. Current DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName', (These are the same settings in MySQL Workbench and mySQL that is running in shared mode) 'HOST': '127.0.0.1:3306', 'USER': 'root', 'PASSWORD': 'DDDDDD', Question: Are there separate configuration settings [options] to remove mysqlclient and replace it with mysql-connector-python-8.0.30? -
Can't fetch from backend - React [closed]
I have the information in the backend (Django) but I can't seem to get it with the methods that I found on google. When I implement the code for all products it works. But when I specify the id it doesn't return anything. I also get a warning in console of: "React Hook useEffect has a missing dependency: 'match.params.id'" Here is the code: function ProductScreen({ match }) { const [product, setProduct] = useState([]) useEffect(() =>{ async function fetchProduct() { const { data } = await axios.get(`/api/products/${match.params.id}`) setProduct(data) } fetchProduct() },[]) Thank you in advance! -
Duplicate tables created in django migrations when using SQL Server schemas
I want to place all Django specific tables and my custom Auth models into the default dbo schema, and have all my different app specific tables in a schema named after the app. Something to note is that all of my app tables will foreign key back to my auth model (I have _created_by and _last_updated_by fields on a base model that all apps inherit from). Basically I want the DB structure to be something like this: DBO - my_custom_auth_table - django_migrations - django_session - django_content_type - etc... APP1 -table1 -table2 APP2 -table1 -table2 In order to achieve this, I tried creating a Login/User pair on the DB server for each app and implemented a DB router. my allow_migrate method: def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == db: return True else: return False my database settings (I will use my doglicense app as an example): default_db_settings = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': 'some_user', 'PASSWORD':'***', 'HOST':'***', 'PORT':'1433', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server', 'extra_params': 'trustServerCertificate=yes'}, } doglicense = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': 'DogLicense', 'PASSWORD':'***', 'HOST':'***', 'PORT':'1433', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server', 'extra_params': 'trustServerCertificate=yes'}, } I have successfully migrated the custom auth app and all of … -
Storing a users name after clicking on a link to display
I'm building a ticketing system using the django framework. Whenever a ticket is filled out and submitted, the support group will go into the support app and see the information on what ticket number, customer name, summary, date created, etc. The ticket number is a link to the details of that ticket. What I would like to do is, whenever a user clicks that link, the ticket is automatically assigned to that user. This helps keeps users from being able to pick and choose which tickets they want to do. The way I have it now is whoever updates the ticket to change the status of the ticket, that person is assigned. I feel my options here with django are limited so if you've got any JS ideas, please feel free to share. -
Display fields based on the request in django-rest-framework serializer
I have a Post model in my Django project. I want to display description field when the user receives the list of posts, and when he receives a post instance, display the body field instead. (Both fields exist separately in the model) here is my Post serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title', 'image', 'description', 'slug'] lookup_field = 'slug' this is my view: class posts(viewsets.ModelViewSet): queryset = Post.published.all() serializer_class = PostSerializer lookup_field = 'slug' I want when the user gets the posts list in /posts/ url, see something like this: [ { "id": 31, "title": "hello-world", "image": { ... }, "description": "post description", "slug": "hello-world" }, ... ] and when get a post instance, see something like this with additional body field and exclude the description field: { "id": 31, "title": "hello-world", "image": { ... }, "body": "post body ...", "slug": "hello-world" } -
raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE) Ubuntu Django
I've created another language (IN-te) on Django application, it is working perfectly fine on my dev machine (MacOS) but when I host it to Ubuntu server, it is giving me following error raise OSError('No translation files found for default language %s.' % settings.LANGUAGE_CODE) OSError: No translation files found for default language IN-te. I have local folder with all necessary files what might be issue here? -
Django - query more than one row returned by a subquery used as an expression error
I have a query and I need to add field using annotate Employees.objects.filter( /* filtering here */ ).annotate( group_ids=Subquery( EmployeesGroups.objects.distinct() .select_related("groups") .values_list("id", flat="True") ) ) I get the next error : Django query more than one row returned by a subquery used as an expression. When I print result of subquery it is something like this: <Queryset [10, 55]> How can I fix this problem? -
Can't change built-in template Django admin
I want to add a button next to the table, by clicking on which a new url will open. I have already written the function itself, but the problem is that I can not make this button. I looked at many answers on this forum, tried many options, but could not solve my problem. My project struct: python_backend ├── cms | └──admin.py | ├── templates | └── cms | └──csv_upload.html | └──emaillisttosends | └──change_list.html └──main_settings └──settings.py My csv_upload.html code: {% extends "admin/change_list.html" %} {% load static %} {% block content %} <a href="upload-csv/">Upload a csv file</a> {{ block.super }} {% endblock %} I want to see this: But i have this: -
Django get manytomany from classbasedview got <QuerySet []>
I need the Lehrer and Gl Lehrer retrieved from Schulverzeichnis, so that Lehrer and GL Lehrer are from their corresponding Schulverzeichnis, any idea ? class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() context['BedarfsBerechnung'] = Bedarfs_und_BesetzungsberechnungTabelle.objects.all() context['JahrgangGebunden'] = JahrgangsgebundenTabelle.objects.all() context['JahrgangUebergreifend'] = JahrgangsuebergreifendTabelle.objects.all() context['FoerderBedarf'] = FoerderbedarfschuelerTabelle.objects.all() context['VorbereitungsKlassen'] = VorbereitungsklassenTabelle.objects.all() context['EinzelIntergration'] = EinzelintegrationTabelle.objects.all() context['SonderPaedagogen'] = SonderpaedagogenbedarfTabelle.objects.all() context['Lehrer'] = LehrerTabelle.objects.all() context['GL_Lehrer'] = GL_LehrerTabelle.objects.all() return context template renders this <QuerySet []> {% for Ansicht in Schulverzeichnis.Lehrer_FK.all %} <li>{{ Ansicht }}</li> {% endfor %} -
Django post_save won't add to ManyToMany Field
I've got these models, and I want to fill an instance of Reporte after it gets saved certain data related to the dates. In the post_save it access the sales made between the dates passed and then it adds them to manytomany field in Reporte but I can't save them to a Reporte instance and I don't understand why class Venta(models.Model): repuesto = models.ForeignKey(Repuestos, models.CASCADE) cantidad = models.IntegerField() fecha_venta = models.DateField() total = models.FloatField(null=True, blank=True) def __str__(self): return f'{self.repuesto} - {self.cantidad} - {self.fecha_venta}' class Reporte(models.Model): fecha_inicio = models.DateField() fecha_fin = models.DateField() ventas = models.ManyToManyField(Venta, null=True, blank=True) estado_de_cuenta = models.FloatField(null=True, blank=True) costo_de_inventario = models.FloatField(null=True, blank=True) deficit_de_productos = models.CharField(max_length=100, null=True, blank=True) @receiver(post_save, sender=Reporte) def guarda_venta(sender, instance, created, **kwargs): if created: vent = Venta.objects.all() ventas_delta = vent.filter(fecha_venta__range=[instance.fecha_inicio, instance.fecha_fin]) instance.ventas.set(ventas_delta) instance.save() Anyone knows what am I doing wrong? -
Django is not imported
I cant understand why is this thing working like that. It can do runserver, but cant do collectstatic, how can i fix it?(I am deploying it) g -
python manage.py collectstatic error: cannot find rest_framework bootstrap.min.css.map (from book 'Django for APIs')
I am reading the book 'Django for APIs' from 'William S. Vincent' (current edition for Django 4.0) In chapter 4, I cannot run successfully the command python manage.py collectstatic. I get the following error: Traceback (most recent call last): File "/Users/my_name/Projects/django/django_for_apis/library/manage.py", line 22, in <module> main() File "/Users/my_name/Projects/django/django_for_apis/library/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/Users/my_name/Projects/django/django_for_apis/library/.venv/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect raise processed whitenoise.storage.MissingFileError: The file 'rest_framework/css/bootstrap.min.css.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x102fa07f0>. The CSS file 'rest_framework/css/bootstrap.min.css' references a file which could not be found: rest_framework/css/bootstrap.min.css.map Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I have the exact same settings like in the book in settings.py: STATIC_URL = "static/" STATICFILES_DIRS = [BASE_DIR / "static"] # new STATIC_ROOT = BASE_DIR / "staticfiles" # new STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # new I couldn't find any explanation for it. maybe someone can point me in the right direction. -
ValueError: unable to configure handler 'loggers'
I was writing code in vscode that logs user activity(logins and logouts) using signals on my django website but it keeps showing this error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 723, in configure_handler klass = self.resolve(cname) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 383, in resolve name = s.split('.') AttributeError: 'NoneType' object has no attribute 'split' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 810, in dictConfig dictConfigClass(config).configure() File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 572, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'loggers' The code i was writing was LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s", 'datefmt': "%Y/%b/%d … -
Does Django have a way for ModelViewSet to represent both parent and child models?
I need to have extra fields in response if they are available, but not all objects of that class have this property. So for example we have class Car(models.Model): brand = model.CharField() wheelcount = model.IntField() class Truck(Car): max_load = model.IntField() class Bus(Car): max_people = model.IntField() and a view class CarView(ReadOnlyModelViewSet): serializer_class = CarSerializer queryset = Car.objects.all() Is there a way to either write CarSerializer to somehow serialize child objects differently, or a way to make view class choose a serializer based on class or additional field(like having an enum CarType)?