I'm trying to add object to my models that are unique and case insensitive so if I add 'car' first and then I try to add 'cAr' it should return an error. I don't know how to that, though.
How can I make this happen?
This is the model:
class Food(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
This is the serializer:
class FoodSerializer(serializers.ModelSerializer):
class Meta:
model = Food
fields = '__all__'
You can Make your custom LowerCharField and Use it in your Models Just import this class
and car and Car can be checked for uniqueness.
Here is my solution.
class LowerCharField(with_metaclass(models.SubfieldBase, models.CharField)):
def __init__(self, *args, **kwargs):
self.is_lowercase = kwargs.pop('lowercase', False)
super(LowerCharField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
value = super(LowerCharField, self).get_prep_value(value)
if self.is_lowercase:
return value.lower()
return value
And You can do this way
class Food(models.Model):
name =LowerCharField(max_length=128, lowercase=True, null=False, unique=True)
def __str__(self):
return self.name
If you want further customization like you may take any input from user i.e car or CAR at the end you may convert to lower and check for uniqueness.
Related
I have a model class in Django which has a ForeignKey referencing the model it actually belongs to:
class Foo(models.Model):
name = models.CharField(max_length=256, verbose_name="Name")
#... some other fields
bar = models.ForeignKey(
"self", on_delete=models.CASCADE, null=True, blank=True
)
def __str__(self):
return self.name
I want to add a custom method in that class which resolves, on the fly, the name in a new field, e.g. bar_resolved when instantiating it in a QuerySet in a view:
from .models import Foo
foo = Foo.objects.all()
# do stuff
I've tried this:
class Foo(models.Model):
name = models.CharField(max_length=256, verbose_name="Name")
#... some other fields
bar = models.ForeignKey(
"self", on_delete=models.CASCADE, null=True, blank=True
)
# preparing the resolved bar field which should contain the 'name' value corresponding to the id:
bar_resolved = models.CharField(
max_length=256,
verbose_name="Bar name resolved",
null=True
)
def __str__(self):
return self.name
def resolve(self):
if self.bar:
self.bar_resolved = self.bar.name
return super(Foo, self).resolve()
Then in my view:
from .models import Foo
foo = Foo.objects.all()
foo.resolve()
but it raises: 'QuerySet' object has no attribute 'resolve'
How could I achieve that? and do I need to hard code a 'resolved' field in my model for that (I think it's overkill to do so)?
I do not understand why would you have a Foreing key referencing self in the database.
Instead of using resolve, you could probably do it on the save long before - i.e. when setting value of "bar"
Another idea that comes to mind is setting it in the __ init__
method of the model link to Stack
hope this helps.
def save(self, force_insert: bool = False, force_update: bool = False) -> None:
if self.field is None:
self.field = "value"
# and so on...
return super().save(force_insert, force_update)
One way is to annotate..[Django-doc] your queryset using F expressions..[Django-doc] with bar's name field:
from django.db.models import F
foos = Foo.objects.annotate(bar_resolved=F("bar__name")).all()
for foo in foos:
print(foo.bar_resolved)
Is there a way to pass paremeters to a Django Rest Framework's SerializerMethodField?
Assume I have the models:
class Owner(models.Model):
name = models.CharField(max_length=10)
class Item(models.Model):
name = models.CharField(max_length=10)
owner = models.ForeignKey('Owner', related_name='items')
itemType = models.CharField(max_length=5) # either "type1" or "type2"
What I need is to return an Owner JSON object with the fields: name, type1items, type2items.
My current solution is this:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = models.Item
fields = ('name', 'itemType')
class OwnerSerializer(serializers.ModelSerializer):
type1items = serializers.SerializerMethodField(method_name='getType1Items')
type2items = serializers.SerializerMethodField(method_name='getType2Items')
class Meta:
model = models.Owner
fields = ('name', 'type1items', 'type2items')
def getType1Items(self, ownerObj):
queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type1")
return ItemSerializer(queryset, many=True).data
def getType2Items(self, ownerObj):
queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type2")
return ItemSerializer(queryset, many=True).data
This works. But it would be much cleaner if I could pass a parameter to the method instead of using two methods with almost the exact code. Ideally it would look like this:
...
class OwnerSerializer(serializers.ModelSerializer):
type1items = serializers.SerializerMethodField(method_name='getItems', "type1")
type2items = serializers.SerializerMethodField(method_name='getItems', "type2")
class Meta:
model = models.Owner
fields = ('name', 'type1items', 'type2items')
def getItems(self, ownerObj, itemType):
queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType=itemType)
return ItemSerializer(queryset, many=True).data
In the docs SerializerMethodField accepts only one parameter which is method_name.
Is there any way to achieve this behaviour using SerializerMethodField? (The example code here is overly simplified so there might be mistakes.)
There is no way to do this with the base field.
You need to write a custom serializer field to support it. Here is an example one, which you'll probably want to modify depending on how you use it.
This version uses the kwargs from the field to pass as args to the function. I'd recommend doing this rather than using *args since you'll get more sensible errors, and flexibility in how you write your function/field definitions.
class MethodField(SerializerMethodField):
def __init__(self, method_name=None, **kwargs):
# use kwargs for our function instead, not the base class
super().__init__(method_name)
self.func_kwargs = kwargs
def to_representation(self, value):
method = getattr(self.parent, self.method_name)
return method(value, **self.func_kwargs)
Using the field in a serializer:
class Simple(Serializer):
field = MethodField("get_val", name="sam")
def get_val(self, obj, name=""):
return "my name is " + name
>>> print(Simple(instance=object()).data)
{'field': 'my name is sam'}
You could just refactor what you have:
class OwnerSerializer(serializers.ModelSerializer):
type1items = serializers.SerializerMethodField(method_name='getType1Items')
type2items = serializers.SerializerMethodField(method_name='getType2Items')
class Meta:
model = models.Owner
fields = ('name', 'type1items', 'type2items')
def getType1Items(self, ownerObj):
return getItems(ownerObj,"type1")
def getType2Items(self, ownerObj):
return getItems(ownerObj,"type2")
def getItems(self, ownerObj, itemType):
queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType=itemType)
return ItemSerializer(queryset, many=True).data
I'm using Django 2.0.2, Python 3.6.4 and PyCharm 2017.3.3
Models: (in models.py)
class Position(models.Model):
title = models.CharField(max_length=50)
gang = models.ForeignKey(Gang, on_delete=models.CASCADE)
description = models.TextField(max_length=20000)
def __str__(self):
return str(self.title) + ', ' + str(self.gang)
class Application(models.Model):
positions = models.ManyToManyField(Position)
applicant = models.ForeignKey(User, on_delete=models.CASCADE)
class Ranking(models.Model):
position = models.ForeignKey(Position, on_delete=models.CASCADE)
applicant = models.ForeignKey(User, on_delete=models.CASCADE)
rank = models.IntegerField(default=3,validators=[
MaxValueValidator(3),
MinValueValidator(1)
])
Form: (in forms.py)
class RankingForm(forms.ModelForm):
rank = forms.IntegerField(max_value=3, min_value=1)
position = forms.ModelMultipleChoiceField(queryset=Application.positions.all())
class Meta:
model = Ranking
exclude = ['applicant']
fields = ('rank', 'position')
def __init__(self, *args, **kwargs):
super(RankingForm, self).__init__(*args, **kwargs)
self.fields['rank'].widget.attrs.update({'class': 'form-control'})
I keep getting the AttributeError in RankingForm from
"position = forms.ModelMultipleChoiceField(queryset=Application.positions.all())"
When i write
class Application(models.Model):
...
def __str__(self):
return str(self.positions.all())
it shows in django-admin as a QuerySet (which works for forms.ModelMultipleChoiceField()), but writing
class Application(models.Model):
...
def __str__(self):
return str(Application.positions.all())
gives me the same error: 'ManyToManyDescriptor' object has no attribute 'all'
Writing
class RankingForm(forms.ModelForm):
...
position = forms.ModelMultipleChoiceField(queryset=Position.objects.all())
works, but this is not what i want the field to display.
I want to make a ModelMultipleChoiceField() with all the positions from a specific application, but this error keeps getting in the way. It seems that just referencing a model doesn't work, but referencing self does?? Any help is greatly appreciated! :)
Btw, I haven't found any good documentation on this problem, but this seems to be the code for related_descriptors.py where ManyToManyDescriptor is located
Evaluating relationships are done with an instance that is an initialized instance of the class.
An instance of the Application.
application = Application.objects.first()
application.positions.all()
Change the form queryset after initialization.
class RankingForm(forms.ModelForm):
rank = forms.IntegerField(max_value=3, min_value=1)
position = forms.ModelMultipleChoiceField(queryset=Positions.objects.none())
class Meta:
model = Ranking
exclude = ['applicant']
fields = ['rank', 'position']
def __init__(self, *args, **kwargs):
super(RankingForm, self).__init__(*args, **kwargs)
self.fields['rank'].widget.attrs.update({'class': 'form-control'})
self.fields['position'].queryset = self.instance.positions.all()
You can access the current instance of your model that the ModelForm object is working with using the instance attribute. You can then use it to create the correct queryset in __init__:
class RankingForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['rank'].widget.attrs.update({'class': 'form-control'})
self.fields['position'].queryset = self.instance.positions.all()
models.py:
import datetime
from django.db import models
from pygments.lexers import get_all_lexers
LEXERS = [item for item in get_all_lexers() if item[1]]
class Classname(models.Model):
class_name = models.CharField(max_length=8)
def __str__(self):
return self.class_name
class Sectionname(models.Model):
class_name = models.ForeignKey(Classname)
section_name = models.CharField(max_length=1, default='A')
def __str__(self):
return self.section_name
class Teachername(models.Model):
field = """ I want to define here a foreign key field(inherited from Sectionname model)which saves the primary key value of row corresponding to two fields (class_name, section_name) above."""
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
class Attendancename(models.Model):
teacher_name = models.ForeignKey(Teachername)
date = models.DateField('Date')
intime = models.TimeField('IN-TIME')
outtime = models.TimeField('OUT-TIME')
def hours_conversion(self):
tdelta = (datetime.datetime.combine(datetime.date.today(),self.outtime) - datetime.datetime.combine(datetime.date.today(),self.intime))
hours, minutes = tdelta.seconds//3600, (tdelta.seconds//60)%60
return '{0}hrs {1}mins'.format(hours, minutes)
def __str__(self):
return "%s" %self.teacher_name
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Classname, Sectionname, Teachername, Attendancename
class ClassnameForm(ModelForm):
class_name = forms.CharField(max_length=8)
class Meta:
model = Classname
fields = ('class_name',)
class SectionnameForm(ModelForm):
class_name = forms.ModelChoiceField(queryset=Classname.objects.all())
class Meta:
model = Sectionname
fields = ('section_name', 'class_name',)
class TeachernameForm(ModelForm):
field = """ Here I also want to do the same thing, I tried to make a form field, which shows value of both 'section_name' and 'class_name' from above model but only saves the value of corresponding row's primary key."""
class Meta:
model = Teachername
fields = ('classname', 'secname', 'teachname',)
class AttendancenameForm(ModelForm):
teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all())
class Meta:
model = Attendancename
fields = ('teacher_name', 'date', 'intime', 'outtime',)
I'm trying to save the 'pk' value of Sectionname model fields('calss_name', 'section_name') into Terachername model's single 'field', I also want to show the both the values to user using form field 'field', but behined the scenes only primary key values needs to be saved.
Is it possible to do so? If it is then how can I implement it in my app?
Please! provide your suggestions....
Thanks! in advance.....
You cannot store two foreign keys to two different tables in a single models.ForeignKey field, and it really wouldn't make any sense (if the reason is not obvious to you then you should learn more about relational model).
But anyway: since a Sectionname belongs to one single Classname, you don't need anything else than the Sectionname pk to get the related Classname:
class Teachername(models.Model):
sectionname = models.ForeignKey(Sectionname)
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
teacher = Teachername.objects.get(pk=XXX)
print teacher, teacher.sectionname, teacher.sectionname.classname
Or if a teacher is supposed to teach more than one section:
class Teachername(models.Model):
sectionnames = models.ManyToMany(Sectionname)
teachname = models.CharField(max_length=50, verbose_name='teacher Name')
def __str__(self):
return self.teachname
teacher = Teachername.objects.get(pk=XXX)
for sectionname in teacher.sectionnames.all():
print teacher, sectionname.classname
I can't find this info in the docs or on the interwebs.
latest django-rest-framework, django 1.6.5
How does one create a ModelSerializer that can handle a nested serializers where the nested model is implemented using multitable inheritance?
e.g.
######## MODELS
class OtherModel(models.Model):
stuff = models.CharField(max_length=255)
class MyBaseModel(models.Model):
whaddup = models.CharField(max_length=255)
other_model = models.ForeignKey(OtherModel)
class ModelA(MyBaseModel):
attr_a = models.CharField(max_length=255)
class ModelB(MyBaseModel):
attr_b = models.CharField(max_length=255)
####### SERIALIZERS
class MyBaseModelSerializer(serializers.ModelSerializer):
class Meta:
model=MyBaseModel
class OtherModelSerializer(serializer.ModelSerializer):
mybasemodel_set = MyBaseModelSerializer(many=True)
class Meta:
model = OtherModel
This obviously doesn't work but illustrates what i'm trying to do here.
In OtherModelSerializer, I'd like mybasemodel_set to serialize specific represenntations of either ModelA or ModelB depending on what we have.
If it matters, I'm also using django.model_utils and inheritencemanager so i can retrieve a queryset where each instance is already an instance of appropriate subclass.
Thanks
I've solved this issue a slightly different way.
Using:
DRF 3.5.x
django-model-utils 2.5.x
My models.py look like this:
class Person(models.Model):
first_name = models.CharField(max_length=40, blank=False, null=False)
middle_name = models.CharField(max_length=80, blank=True, null=True)
last_name = models.CharField(max_length=80, blank=False, null=False)
family = models.ForeignKey(Family, blank=True, null=True)
class Clergy(Person):
category = models.IntegerField(choices=CATEGORY, blank=True, null=True)
external = models.NullBooleanField(default=False, null=True)
clergy_status = models.ForeignKey(ClergyStatus, related_name="%(class)s_status", blank=True, null=True)
class Religious(Person):
religious_order = models.ForeignKey(ReligiousOrder, blank=True, null=True)
major_superior = models.ForeignKey(Person, blank=True, null=True, related_name="%(class)s_superior")
class ReligiousOrder(models.Model):
name = models.CharField(max_length=255, blank=False, null=False)
initials = models.CharField(max_length=20, blank=False, null=False)
class ClergyStatus(models.Model):
display_name = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
Basically - The base model is the "Person" model - and a person can either be Clergy, Religious, or neither and simply be a "Person". While the models that inherit Person have special relationships as well.
In my views.py I utilize a mixin to "inject" the subclasses into the queryset like so:
class PersonSubClassFieldsMixin(object):
def get_queryset(self):
return Person.objects.select_subclasses()
class RetrievePersonAPIView(PersonSubClassFieldsMixin, generics.RetrieveDestroyAPIView):
serializer_class = PersonListSerializer
...
And then real "unDRY" part comes in serializers.py where I declare the "base" PersonListSerializer, but override the to_representation method to return special serailzers based on the instance type like so:
class PersonListSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
if isinstance(instance, Clergy):
return ClergySerializer(instance=instance).data
elif isinstance(instance, Religious):
return ReligiousSerializer(instance=instance).data
else:
return LaySerializer(instance=instance).data
class Meta:
model = Person
fields = '__all__'
class ReligiousSerializer(serializers.ModelSerializer):
class Meta:
model = Religious
fields = '__all__'
depth = 2
class LaySerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = '__all__'
class ClergySerializer(serializers.ModelSerializer):
class Meta:
model = Clergy
fields = '__all__'
depth = 2
The "switch" happens in the to_representation method of the main serializer (PersonListSerializer). It looks at the instance type, and then "injects" the needed serializer. Since Clergy, Religious are all inherited from Person getting back a Person that is also a Clergy member, returns all the Person fields and all the Clergy fields. Same goes for Religious. And if the Person is neither Clergy or Religious - the base model fields are only returned.
Not sure if this is the proper approach - but it seems very flexible, and fits my usecase. Note that I save/update/create Person thru different views/serializers - so I don't have to worry about that with this type of setup.
I was able to do this by creating a custom relatedfield
class MyBaseModelField(serializers.RelatedField):
def to_native(self, value):
if isinstance(value, ModelA):
a_s = ModelASerializer(instance=value)
return a_s.data
if isinstance(value, ModelB):
b_s = ModelBSerializer(instance=value)
return b_s.data
raise NotImplementedError
class OtherModelSerializer(serializer.ModelSerializer):
mybasemodel_set = MyBaseModelField(many=True)
class Meta:
model = OtherModel
fields = # make sure we manually include the reverse relation (mybasemodel_set, )
I do have concerns that instanting a Serializer for each object is the reverse relation queryset is expensive so I'm wondering if there is a better way to do this.
Another approach i tried was dynamically changing the model field on MyBaseModelSerializer inside of __init__ but I ran into the issue described here:
django rest framework nested modelserializer
Using Django 3.1, I found that it is possible to override get_serializer instead of get_serializer_class, in which case you can access the instance as well as self.action and more.
By default get_serializer will call get_serializer_class, but this behavior can be adjusted to your needs.
This is cleaner and easier than the solutions proposed above, so I'm adding it to the thread.
Example:
class MySubclassViewSet(viewsets.ModelViewSet):
# add your normal fields and methods ...
def get_serializer(self, *args, **kwargs):
if self.action in ('list', 'destroy'):
return MyListSerializer(args[0], **kwargs)
if self.action in ('retrieve', ):
instance = args[0]
if instance.name.contains("really?"): # or check if instance of a certain Model...
return MyReallyCoolSerializer(instance)
else return MyNotCoolSerializer(instance)
# ...
return MyListSerializer(*args, **kwargs) # default
I'm attempting to use a solution that involves different serializer subclasses for the different model subclasses:
class MyBaseModelSerializer(serializers.ModelSerializer):
#staticmethod
def _get_alt_class(cls, args, kwargs):
if (cls != MyBaseModel):
# we're instantiating a subclass already, use that class
return cls
# < logic to choose an alternative class to use >
# in my case, I'm inspecting kwargs["data"] to make a decision
# alt_cls = SomeSubClass
return alt_cls
def __new__(cls, *args, **kwargs):
alt_cls = MyBaseModel.get_alt_class(cls, args, kwargs)
return super(MyBaseModel, alt_cls).__new__(alt_cls, *args, **kwargs)
class Meta:
model=MyBaseModel
class ModelASerializer(MyBaseModelSerializer):
class Meta:
model=ModelA
class ModelBSerializer(MyBaseModelSerializer):
class Meta:
model=ModelB
That is, when you try and instantiate an object of type MyBaseModelSerializer, you actually end up with an object of one of the subclasses, which serialize (and crucially for me, deserialize) correctly.
I've just started using this, so it's possible that there are problems I've not run into yet.
I found this post via Google trying to figure out how to handle multiple table inheritance without having to check the model instance type. I implemented my own solution.
I created a class factory and a mixin to generate the serializers for the child classes with the help of InheritanceManger from django-model-utils.
models.py
from django.db import models
from model_utils import InheritanceManager
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
# Use the InheritanceManager for select_subclasses()
objects = InheritanceManager()
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
serializers.py
from rest_framework import serializers
from .models import Location
def modelserializer_factory(model, class_name='ModelFactorySerializer',
meta_cls=None, **kwargs):
"""Generate a ModelSerializer based on Model"""
if meta_cls is None:
# Create a Meta class with the model passed
meta_cls = type('Meta', (object,), dict(model=model))
elif not hasattr(meta_cls, 'model'):
# If a meta_cls is provided but did not include a model,
# set it to the model passed into this function
meta_cls.model = model
# Create the ModelSerializer class with the Meta subclass
# we created above; also pass in any additional keyword
# arguments via kwargs
ModelFactorySerializer = type(class_name, (serializers.ModelSerializer,),
dict(Meta=meta_cls, **kwargs))
ModelFactorySerializer.__class__.__name__ = class_name
return ModelFactorySerializer
class InheritedModelSerializerMixin:
def to_representation(self, instance):
# Get the model of the instance
model = instance._meta.model
# Override the model with the inherited model
self.Meta.model = model
# Create the serializer via the modelserializer_factory
# This will use the name of the class this is mixed with.
serializer = modelserializer_factory(model, self.__class__.__name__,
meta_cls=self.Meta)
# Instantiate the Serializer class with the instance
# and return the data
return serializer(instance=instance).data
# Mix in the InheritedModelSerializerMixin
class LocationSerializer(InheritedModelSerializerMixin, serializers.ModelSerializer):
class Meta:
model = Location # 'model' is optional since it will use
# the instance's model
exclude = ('serves_pizza',) # everything else works as well
depth = 2 # including depth
views.py
from .models import Location
from .serializers import LocationSerializer
# Any view should work.
# This is an example using viewsets.ReadOnlyModelViewSet
# Everything else works as usual. You will need to chain
# ".select_subclasses()" to the queryset to select the
# child classes.
class LocationViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Location.objects.all().select_subclasses()
serializer_class = LocationSerializer