Django REST: getting serializer model field's default value - python

Using Django and REST for my project. At some point I need to access serializer model's field default value (since REST doesn't set default values). The code looks like this:
# try to get default from model, if it is not set then try to get default from serializer
default = serializer.Meta.model._meta.get_field(input_instance.field_name).default
I think this is ugly.
Is there any way to shorten this expression?

Related

Unable to create Model without fields in Django rest framework

I am trying to create a model in Django rest framework, without any field information as I'm using MongoDB which doesn't have any fixed fields
twitterdashmodel.py-----
class TwitterMaster(models.Model):
I need a way out so that I can use model to make query functionality from function based views. I am novice to Django rest framework. Need a guidance/solution to it
You usually write pass [python-doc] to end a scope without any statements:
class TwitterMaster(models.Model):
pass
# … something else …
Note that Django will however add a field itself: an AutoField with the name id that is the primary key of the model. For more information, see the automatic primary key fields section of the documentation.
You can also use Python Doc String
class TwitterMaster(models.Model):
"""TwitterMaster do ...."""

How do I add an index to Django's User model

My Django project always sorts Users by their first name, and I'd like to create an index on the field, but since it's a Django-defined model, I can't add it into the built-in code. First, does Django already have an index on the first name field? If not, can I add an index somehow? I know I could subclass the User model and handle all of the intricacies with that, but is there another way?
Based on the source code https://github.com/django/django/blob/master/django/contrib/auth/models.py#L320 , There's no db_index on the first name field.
You should Extending Django’s default User to have your own db_index
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-django-s-default-user

How can I reuse django form for searching?

I am programming an application in django, and I have a model where I defined some fields that are necessary to be filled. This way, when te user doesn't fill one of these fields, Django authomatically indicates to the user to fill it to create the specific object defined by the model.
But myquestion comes here: I want to reuse the same form to search objects defined by that model. And in this case, all the fields that before were necessary, now are OPTIONAL. But, as I have already defined the model so that the fields are necessary, django doesn´t let me define those fields as optional.
Is there any way to reuse that form where the fields are necessary, but making them OPTIONAL? Or I must create another different model or form in html? I know that creating another form manually in the html code the problem is solver, but I have curiosity to know if it can be reused.
Thank you so much!
You can programmatically change properties of a field within a form using its fields dictionary. So you could create a new form class that is derived from your current form class and in its __init__ set the required property of the fields you desired to be optional to be False like so:
self.fields['title'].required = False

django-rest-framework clarification on field "required" option

I have the following serializer:
class ReqSerializer(serializers.ModelSerializer):
class Meta:
model = Earth
fields = ('area', )
and this model:
class Earth(models.Model):
area = models.IntegerField(default=0)
According to django-rest-framework Serializer fields the "required" option is
set to True by default which means if I try to validate the serializer without "area" field in the input,
I should get This field is required error. But is_valid() is passed and the model gets created with default area=0. However, Using this:
extra_kwargs = {
area': {'required': True},
}
Would solve the issue but why? What could change this behavior? Why the default "required=True"
has no effect?
Update:
I just noticed that if I remove the default=0 from the model, it will work as expected. Now the question is why setting default on model field cancels the required=True on serializer.
I believe your problem here is that the field is being automatically generated by Django REST framework, while the docs are coming from the perspective of you manually creating the field on the serializer.
According to django-rest-framework Serializer fields the "required" option is set to True by default
This is correct for fields that you specify on your own on the serializer. In the case of automatically generated fields, Django REST framework tries to determine the serializer field options that best match the model field, similar to how the Django forms does it for form fields. For serializer fields, this is largely undocumented at the moment so there is nothing that I can point you to.
But is_valid() is passed and the model gets created with default area=0. 
This is because Django REST framework determines that the field has a default value, at which point is knows input is not strictly required because the model field will automatically give a default value in the event that the user passes nothing in. Of course, if you pass something into the serializer on creation, the value will be used instead of the default, which is what you would expect if you were manually creating the model.
Would solve the issue but why? What could change this behavior? Why the default "required=True" has no effect?
This will fix your issue because it is manually overriding the required=False that is set on the automatically generated serializer field. In Django REST framework 3.0, you can confirm that by calling repr(ReqSerializer()) and looking at the the automatically generated field.
I just noticed that if I remove the default=0 from the model, it will work as expected.
This is because Django REST framework no longer determines the default and adds the required=True to the serializer, like you were expecting.

How I can use correctly django ModelChoiceField

I'm a newbie and right now I'm using Django forms to show some fields. One of these fields is a ModelChoiceField this show correctly model data, but I don´t know how I can fill a CharField later of select a option in the ModelChoiceField.
How I can make send the value of option selected for obtain the data that i need for later show this in a CharField, this is possible make directly from a djangoForm or do I need a new view to return the value?
There are two ways to achieve what you want I think:
Provide an initial value for your form value.
Bind your form to some data.
See this related stack overflow to provide initial values.
See Django's documentation on forms for binding data. There are two kinds of form states: bound and unbound. To create a bound form, you just need to create an instance of your form with some data: MyForm({'data-key1': 'data-value1', ...}).

Categories