Can Django contribute_to_class method be used with abstract models? - python

Is there a way to use contribute_to_class method with abstract models, such that it would be executed separately for each child?
I have the following models:
class BaseHistoryModel(Model):
change = JSONField(blank=True, verbose_name=_('Change'))
comment = models.TextField(blank=True)
class Meta:
abstract = True
class HistoryHelper:
def contribute_to_class(self, cls, *_args):
self.create_history_model(cls)
def create_history_model(self, cls):
attrs = {'__module__': cls.__module__}
history_model = type(
'{}{}'.format(sender.__name__, 'History'),
(BaseHistoryModel, ), attrs
)
history_model.target = models.ForeignKey(cls)
return history_model
class BaseModel(models.Model):
name = models.CharField()
history = HistoryHelper()
class Meta:
abstract = True
I need it to create a separate history model for every child of BaseModel, but when I run makemigrations all I get is one change which creates history model for the abstract BaseModel. Is there a way to somehow get it to create one for every child?

Related

change Class property properties (verbose_name exmpl.) from base Django model

I have an abstract class with name and slug field.when i inherit from another class i want to change verbose_name parameter according to that class. How can I set this properties? I want to set the verbose_name parameter of the name field to "foo". but I want to use different parameter data for two different classes.
An example:
For ProductModel name field verbose_name="Foo"
For CategoryModel name field verbose_name="Poo"
class BaseProductModel(models.Model):
name = models.CharField(max_length=200)
slug = AutoSlugField(populate_from="name",unique=True,verbose_name="Slug")
class Meta:
abstract=True
class ProductModel(BaseProductModel):
# I want to set the verbose_Name parameter of the name field to "foo".
#The two fields (name and slug) come from the inherited (BaseProductModel) class.
description = models.TextField(max_length=500,verbose_name="Detay")
class CategoryModel(BaseProductModel):
# The two fields (name and slug) come from the inherited (BaseProductModel) class.
# I want to set the verbose_Name parameter of the name field to "Poo".
def __str__(self):
return self.name
You can do this in two ways
First, works only for abstract classes, otherwise it will change verbose_name of parent class too:
class ProductModel(BaseProductModel):
# I want to set the verbose_Name parameter of the name field to "foo".
#The two fields (name and slug) come from the inherited (BaseProductModel) class.
description = models.TextField(max_length=500,verbose_name="Detay")
ProductModel.get_field('name').verbose_name = 'Foo'
And second, do that in the __init__ method:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
field = self._meta.get_field('name')
field.verbose_name = 'Foo'

Parametrize a Python class

Is there any way to parametrize a class in Python? The parametrized class may look something like this:
class FIELDSerializer:
FIELD = serializers.CharField(source='get_FIELD_display', required=False)
class Meta:
model = None
fields = {FIELD}
Which would need to create the following three classes:
class NameSerializer:
name = serializers.CharField(source='get_name_display', required=False)
class Meta:
model = None
fields = {'name'}
class CategorySerializer:
category = serializers.CharField(source='get_category_display', required=False)
class Meta:
model = None
fields = {'category'}
class StateSerializer:
state = serializers.CharField(source='get_state_display', required=False)
class Meta:
model = None
fields = {'state'}
Is this possible or not?
You can do what you want with a factory function, although it's not completely trivial to get the internal variables (attributes) as you want them:
def factory(FIELDname):
class FIELDSerializer:
class Meta:
model = None
fields = {FIELDname}
settatr(FIELDSerializer, FIELDname, serializers.CharField(source=f'get_{FIELDname}_display', required=False))
return FIELDSerializer
CategorySerializer = factory('category')
StateSerializer = factory('state')
NameSerializer = factory('name')
The setattr allows us to set the name of attribute to the FIELDname string. (Thanks to #Code-Apprentice and #juanpa.arrivillaga for this idea.)
I don't know if there's any easy way to avoid the repetition of the field name and the desired class name when you call the factory without using something like exec (which is perfectly legal but usually leaves programmers with a bad taste in their mouths).

Defining an Abstract model with a ForeignKey to another Abstract model

I'm trying to build two abstract classes called SurveyQuestionBase and SurveyResponseBase that will serve as templates to quickly define new concrete Models for implementing specific surveys on our website. The issue I am having is in enforcing that the SurveyResponseBase model, when made concrete, should define a ForeignKey to a concrete model of SurveyQuestionBase.
Django does not allow us to define ForeignKeys to abstract classes so I cannot, for instance, do this:
question = models.ForeignKey(SurveyQuestionBase)
Neither can I have it as None or app_label.ModelName for similar reasons.
One hacky fix is to create a new concrete model SurveyQuestionConcrete and make the ForeignKey point to this: question = models.ForeignKey(concrete_model), combined with validation to ensure this model is replaced.
Is there a cleaner way to achieve the same thing? All I need to do is ensure that when someone defines a concrete model from SurveyResponseBase they include a ForeignKey to a concrete model defined from SurveyQuestionBase
Here's the full code:
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
# Implementation borrows from: https://github.com/jessykate/django-survey/
class SurveyQuestionBase(models.Model):
TEXT = 'text'
INTEGER = 'integer'
RADIO = 'radio'
SELECT = 'select'
MULTI_SELECT = 'multi-select'
ANSWER_TYPE_CHOICES = (
(INTEGER, 'Integer',),
(TEXT, 'Text',),
(RADIO, 'Radio',),
(SELECT, 'Select',),
(MULTI_SELECT, 'Multi-Select',),
)
question = models.TextField()
required = models.BooleanField()
question_type = models.CharField(choices=ANSWER_TYPE_CHOICES, max_length=20)
class Meta:
abstract = True
class SurveyResponseBase(models.Model):
"""
concrete_question_model: 'app_label.Model' - Define the concrete model this question belongs to
"""
concrete_model = 'SurveyQuestionBase'
question = models.ForeignKey(concrete_model)
response = models.TextField()
class Meta:
abstract = True
Two solutions (both working) to this problem:
The first solution involves using GenericForeignKey. The second is more interesting and involves generating the SurveyResponseBase dynamically.
Solution 1: Using GenericForeignKey
class SurveyQuestionBase(models.Model):
TEXT = 'text'
INTEGER = 'integer'
RADIO = 'radio'
SELECT = 'select'
MULTI_SELECT = 'multi-select'
ANSWER_TYPE_CHOICES = (
(INTEGER, 'Integer',),
(TEXT, 'Text',),
(RADIO, 'Radio',),
(SELECT, 'Select',),
(MULTI_SELECT, 'Multi-Select',),
)
question = models.TextField()
required = models.BooleanField()
question_type = models.CharField(choices=ANSWER_TYPE_CHOICES, max_length=20)
class Meta:
abstract = True
#classmethod
def get_subclasses(cls, *args, **kwargs):
for app_config in apps.get_app_configs():
for app_model in app_config.get_models():
model_classes = [c.__name__ for c in inspect.getmro(app_model)]
if cls.__name__ in model_classes:
yield app_model
class SurveyResponseBase(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=get_content_choices)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
response = models.TextField()
class Meta:
abstract = True
def get_content_choices():
query_filter = None
for cls in SurveyQuestionBase.get_subclasses():
app_label, model = cls._meta.label_lower.split('.')
current_filter = models.Q(app_label=app_label, model=model)
if query_filter is None:
query_filter = current_filter
else:
query_filter |= current_filter
return query_filter
Solution 2: Dynamic base class generation
class SurveyQuestionBase(models.Model):
TEXT = 'text'
INTEGER = 'integer'
RADIO = 'radio'
RATING = 'rating'
SELECT = 'select'
MULTI_SELECT = 'multi-select'
QUESTION_TYPES = (
(INTEGER, 'Integer'),
(TEXT, 'Text'),
(RADIO, 'Radio'),
(RATING, 'Rating'),
(SELECT, 'Select'),
(MULTI_SELECT, 'Multi-Select'),
)
CHOICE_TYPES = (RADIO, RATING, SELECT, MULTI_SELECT)
question = models.TextField()
required = models.BooleanField()
question_type = models.CharField(choices=QUESTION_TYPES, max_length=20)
choices = models.TextField(blank=True, null=True)
choices.help_text = """
If the question type is "Radio," "Select," or "Multi-Select",
provide a comma-separated list of options for this question
"""
class Meta:
abstract = True
Meta = type('Meta', (object,), {'abstract': True})
def get_response_base_class(concrete_question_model):
"""
Builder method that returns the SurveyResponseBase base class
Args:
concrete_question_model: Concrete Model for SurveyQuestionBase
Returns: SurveyResponseBase Class
"""
try:
assert SurveyQuestionBase in concrete_question_model.__bases__
except AssertionError:
raise ValidationError('{} is not a subclass of SurveyQuestionBase'.format(concrete_question_model))
attrs = {
'question': models.ForeignKey(concrete_question_model, related_name='responses'),
'response': models.TextField(),
'__module__': 'survey_builder.models',
'Meta': Meta(),
}
return type('SurveyResponseBase', (models.Model,), attrs)
We decided to go ahead with Solution 2 since the GenericForeignKeys approach requires an additional ContentType selection.
I believe you can't do that because the ForeignKey doesn't know what actual model to point to.
You may be looking for GenericForeignKey (https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations). It allows you to define that relationship properly.

django rest framework abstract class serializer

I have some models like these:
class TypeBase(models.Model):
name = models.CharField(max_length=20)
class Meta:
abstract=True
class PersonType(TypeBase):
pass
class CompanyType(TypeBase):
pass
Having this, I want to create just one serializer that holds all these field types (serialization, deserialization, update and save).
To be more specific, I want only one serializer (TypeBaseSerializer) that print the Dropdown on the UI, serialize the json response, deserialize it on post and save it for all my based types.
Something like this:
class TypeBaseSerializer(serializers.Serializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
Is it possible?
I think the following approach is more cleaner. You can set "abstract" field to true for the base serializer and add your common logic for all child serializers.
class TypeBaseSerializer(serializers.ModelSerializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
abstract = True
def func(...):
# ... some logic
And then create child serializers and use them for data manipulation.
class PersonTypeSerializer(TypeBaseSerializer):
class Meta:
model = PersonType
fields = ('id', 'name')
class CompanyTypeSerializer(TypeBaseSerializer):
class Meta:
model = CompanyType
fields = ('id', 'name')
Now you can use the both of these serializers normally for every model.
But if you really want to have one serializers for both the models, then create a container model and a serializer for him too. That is much cleaner :)
You can't use a ModelSerializer with an abstract base model.
From restframework.serializers:
if model_meta.is_abstract_model(self.Meta.model):
raise ValueError(
'Cannot use ModelSerializer with Abstract Models.'
)
I wrote a serializer_factory function for a similar problem:
from collections import OrderedDict
from restframework.serializers import ModelSerializer
def serializer_factory(mdl, fields=None, **kwargss):
""" Generalized serializer factory to increase DRYness of code.
:param mdl: The model class that should be instanciated
:param fields: the fields that should be exclusively present on the serializer
:param kwargss: optional additional field specifications
:return: An awesome serializer
"""
def _get_declared_fields(attrs):
fields = [(field_name, attrs.pop(field_name))
for field_name, obj in list(attrs.items())
if isinstance(obj, Field)]
fields.sort(key=lambda x: x[1]._creation_counter)
return OrderedDict(fields)
# Create an object that will look like a base serializer
class Base(object):
pass
Base._declared_fields = _get_declared_fields(kwargss)
class MySerializer(Base, ModelSerializer):
class Meta:
model = mdl
if fields:
setattr(Meta, "fields", fields)
return MySerializer
You can then use the factory to produce serializers as needed:
def typebase_serializer_factory(mdl):
myserializer = serializer_factory(
mdl,fields=["id","name"],
#owner=HiddenField(default=CurrentUserDefault()),#Optional additional configuration for subclasses
)
return myserializer
Now instanciate different subclass serializers:
persontypeserializer = typebase_serializer_factory(PersonType)
companytypeserializer = typebase_serializer_factory(CompanyType)
As already mentioned in Sebastian Wozny's answer, you can't use a ModelSerializer with an abstract base model.
Also, there is nothing such as an abstract Serializer, as some other answers have suggested. So setting abstract = True on the Meta class of a serializer will not work.
However you need not use use a ModelSerializer as your base/parent serializer. You can use a Serializer and then take advantage of Django's multiple inheritance. Here is how it works:
class TypeBaseSerializer(serializers.Serializer):
# Need to re-declare fields since this is not a ModelSerializer
name = serializers.CharField()
id = serializers.CharField()
class Meta:
fields = ['id', 'name']
def someFunction(self):
#... will be available on child classes ...
pass
class PersonTypeSerializer(TypeBaseSerializer, serializers.ModelSerializer):
class Meta:
model = PersonType
fields = TypeBaseSerializer.Meta.fields + ['another_field']
class CompanyTypeSerializer(TypeBaseSerializer, serializers.ModelSerializer):
class Meta:
model = CompanyType
fields = TypeBaseSerializer.Meta.fields + ['some_other_field']
So now since the fields name and id are declared on the parent class (TypeBaseSerializer), they will be available on PersonTypeSerializer and since this is a child class of ModelSerializer those fields will be populated from the model instance.
You can also use SerializerMethodField on the TypeBaseSerializer, even though it is not a ModelSerializer.
class TypeBaseSerializer(serializers.Serializer):
# you will have to re-declare fields here since this is not a ModelSerializer
name = serializers.CharField()
id = serializers.CharField()
other_field = serializers.SerializerMethodField()
class Meta:
fields = ['id', 'name', 'other_field']
def get_other_field(self, instance):
# will be available on child classes, which are children of ModelSerializers
return instance.other_field
Just iterating a bit over #adki's answer:
it is possible to skip model for TypeBaseSerializer;
derived serializers can refer to TypeBaseSerializer.Meta, so you would change them in a single place.
class TypeBaseSerializer(serializers.Serializer):
class Meta:
fields = ('id', 'name', 'created')
abstract = True
def func(...):
# ... some logic
class PersonTypeSerializer(TypeBaseSerializer):
class Meta:
model = PersonType
fields = TypeBaseSerializer.Meta.fields + ('age', 'date_of_birth')
class CompanyTypeSerializer(TypeBaseSerializer):
class Meta:
model = CompanyType
fields = TypeBaseSerializer.Meta.fields

django has more than 1 foreignkey error

My models file works just fine. As soon as I replace every models.Model with MyModel (a child-class of models.Model), one of my models raises a
<class 'puppy.cms.models.Appearance'> has more than 1 ForeignKey to <class 'puppy.cms.models.Segment'>
exception. The only thing that I am doing in the child class is override the clean method.
What could I be doing wrong?
class SansHashUrl(object):
""" Upon each call to clean, iterates over every field,
and deletes all '#/' and '#!/' occurances.
IMPORTANT: This mixin must be listed first in the inheritance list to work
properly. """
def clean(self):
attrs = (field.attname for field in self.__class__._meta.fields
if isinstance(field, models.CharField)
or isinstance(field, models.TextField))
for attr in attrs:
attr_value = self.__getattribute__(attr)
tokens = attr_value.split()
for i, token in enumerate(tokens):
if has_internal_domain(token):
suggested_url = re.sub('#!?/','', token)
tokens[i] = suggested_url
self.__setattr__(attr, ' '.join(tokens))
class MyModel(SansHashUrl, models.Model):
pass
Model that throws the error:
class Appearance(MyModel):
appearance_type = models.CharField(max_length=20,
choices=APPEARANCE_TYPE_CHOICES)
person = models.ForeignKey(Person, related_name='person_appearance')
item = models.ForeignKey(ManagedItem)
class Meta:
unique_together = (('person', 'item'),)
def __unicode__(self):
return self.person.__unicode__()
In reference to:
class Segment(Story, HasStatsTags, HasFullUrl):
...
It might be useful to note that Story is a subclass of ManagedItem (a subclass of MyModel).
You need to declare MyModel (and probably ManagedItem) as an abstract model in its Meta class, otherwise Django will create a separate table for them and define FKs between them.
class MyModel(SansHashUrl, models.Model):
class Meta:
abstract = True

Categories