I've got proxy classes which have been created mainly to implement custom filtering, but there are some other fairly small custom methods as well, and they will be expanded to provide other custom logic as well.
So say I have models:
class Videos(models.Model):
title = models.CharField(max_length=200)
publisher = models.Charfield(max_length=100)
release_date = models.DateField()
class Superheroes(Videos):
objects = SuperheroesManager()
class Meta:
proxy = True
class Recent(Videos):
objects = RecentManager()
class Meta:
proxy = True
and model managers:
class SuperheroesManager():
def get_queryset(self):
return super().get_queryset().filter(publisher__in=['Marvel','DC'])
class RecentManager():
def get_queryset(self):
return super().get_queryset().filter(release_date__gte='2020-01-01')
On the front end a user may pick a category which corresponds to one of the proxy classes. What would be the best way to maintain a mapping between the category which is passed to the view and the associated proxy class?
Currently I have an implicit dependency whereby the category name supplied by the front end must be the same as the proxy class name, allowing for a standard interface in the view:
def index(request, report_picked)
category = getattr(sys.modules[__name__], report_picked)
videos = category.objects.all()
I'd like to move away from this implicit dependency, but not sure what the best way would be.
I wouldn't want to maintain a dictionary and can't use a factory method either as that should return a fully initialised object whereas I just need the class returned.
What would be the best way to implement this?
I've decided to set the category name used by the front end as a class variable:
class Superheroes(Videos):
category = 'superheroes'
objects = SuperheroesManager()
class Meta:
proxy = True
And so the view just loops through all the models, and returns the model whose category matches the provided value from the front end:
from django.apps import apps
def index(request, report_picked):
for model in apps.get_models():
try:
print(f"Report picked: {report_picked}, model: {model.name}")
if model.category == report_picked.lower():
category = model
break
except AttributeError:
pass
I'd be curious to know if there is any better alternatives though.
Django allows us to use '%(class)s' to automatically create related name from mixins. But when I have a ClassName I'd rather access it using class_name, not classname. I know it's only semantics but I was wondering if it's possible to adjust model field to make it snake case instead.
I was browsing through django.db.models.fields but I can't find where the class interpolation is happening.
Example code
from django.db import models
class User(models.Model):
pass
class UserRelatedMixin(models.Model):
user = models.OneToOneField(
to=User,
parent_link=True,
on_delete=models.CASCADE,
related_name='%(class)s',
related_query_name="%(class)s",
)
class Meta:
abstract = True
class HomeAddress(UserRelatedMixin):
pass
user = User.objects.first()
What I have
user.homeaddress
What I want instead
user.home_address
Right now I'm using a #property but it won't allow ORM queries so it's a partial solution.
I have an abstract mixin class that adds a Django model field to any concrete class that inherits from it.
At class initialisation - when makemigrations is run - I'd like the inheriting class to define whether an inherited field is required or optional via the blank= True or False property.
I've tried various Meta and __new__ approaches, but can't figure out how the abstract mixin class can get the information from the inheriting class.
Here's a naive attempt:
from django.db import models
class DescriptionMixin(models.Model):
class Meta:
abstract = True
description = models.TetxField(
# how to get value here?
blank=inheriting_class.description_required
)
class OptionalDescription(DescriptionMixin, SomeOtherClass):
class Meta:
verbose_name = 'Optional description'
description_required = False
class RequiredDescription(DescriptionMixin, SomeOtherClass):
class Meta:
verbose_name = 'Required description'
description_required = True
Thanks in advance for any help offered.
You can't do this at the database level. makemigrations doesn't actually initialise your models to create the migration files.
But since you're trying to enforce this on a TextField, which cannot be enforced at the database level anyway (blank is only used when validating a model through the full_clean() method), you could just override the clean() method on the DescriptionMixin, checking the value of self.blank and raising a ValidationError appropriately.
Solved using this (it's actually Wagtail on top of Django):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
self._meta.get_field('description').blank = not getattr(self, 'description_required', False)
I'm trying to create a reusable app where I define some abstract models, and some concrete versions of those models that the user can use if they don't want to inherit the models themselves. If the user does want to create their own subclasses then I don't want Django to create these concrete models.
This is the solution I have at the moment:
myapp/abstract.py
class AbstractModel1:
class Meta:
abstract = True
field1 = models.CharField(max_length=255)
class AbstractModel2:
class Meta:
abstract = True
field1 = models.CharField(max_length=255)
field2 = models.ForeignKey(getattr(settings, 'ABSTRACTMODEL1_OVERRIDE', 'myapp.ConcreteModel1'))
myapp/models.py
if not hasattr(settings, 'ABSTRACTMODEL1_OVERRIDE'):
class ConcreteModel1(AbstractModel1):
pass
if not hasattr(settings, 'ABSTRACTMODEL2_OVERRIDE'):
class ConcreteModel2(AbstractModel2):
pass
Then in the user's app, they can either use the concrete models as provided, or if not then they can create their own subclasses of the model like so:
userapp/models.py
class CustomModel1(AbstractModel1):
extrafield1 = models.CharField(max_length=255)
userapp/settings.py
ABSTRACTMODEL1_OVERRIDE = "userapp.CustomModel1"
Is this the best way to achieve this? Am I setting myself up for difficulties when trying to migrate changes in the subclassed models? What if the user wants to use the provided concrete classes first then migrate to a custom class?
I'm looking to do this:
class Place(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class LongNamedRestaurant(Place): # Subclassing `Place`.
name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length.
food_type = models.CharField(max_length=25)
This is the version I would like to use (although I'm open to any suggestion):
http://docs.djangoproject.com/en/dev/topics/db/models/#id7
Is this supported in Django? If not, is there a way to achieve similar results?
Updated answer: as people noted in comments, the original answer wasn't properly answering the question. Indeed, only the LongNamedRestaurant model was created in database, Place was not.
A solution is to create an abstract model representing a "Place", eg. AbstractPlace, and inherit from it:
class AbstractPlace(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class Meta:
abstract = True
class Place(AbstractPlace):
pass
class LongNamedRestaurant(AbstractPlace):
name = models.CharField(max_length=255)
food_type = models.CharField(max_length=25)
Please also read #Mark answer, he gives a great explanation why you can't change attributes inherited from a non-abstract class.
(Note this is only possible since Django 1.10: before Django 1.10, modifying an attribute inherited from an abstract class wasn't possible.)
Original answer
Since Django 1.10 it's
possible!
You just have to do what you asked for:
class Place(models.Model):
name = models.CharField(max_length=20)
rating = models.DecimalField()
class Meta:
abstract = True
class LongNamedRestaurant(Place): # Subclassing `Place`.
name = models.CharField(max_length=255) # Notice, I'm overriding `Place.name` to give it a longer length.
food_type = models.CharField(max_length=25)
No, it is not:
Field name “hiding” is not permitted
In normal Python class inheritance, it is permissible for a child
class to override any attribute from the parent class. In Django, this
is not permitted for attributes that are Field instances (at least,
not at the moment). If a base class has a field called author, you
cannot create another model field called author in any class that
inherits from that base class.
That is not possible unless abstract, and here is why: LongNamedRestaurant is also a Place, not only as a class but also in the database. The place-table contains an entry for every pure Place and for every LongNamedRestaurant. LongNamedRestaurant just creates an extra table with the food_type and a reference to the place table.
If you do Place.objects.all(), you also get every place that is a LongNamedRestaurant, and it will be an instance of Place (without the food_type). So Place.name and LongNamedRestaurant.name share the same database column, and must therefore be of the same type.
I think this makes sense for normal models: every restaurant is a place, and should have at least everything that place has. Maybe this consistency is also why it was not possible for abstract models before 1.10, although it would not give database problems there. As #lampslave remarks, it was made possible in 1.10. I would personally recommend care: if Sub.x overrides Super.x, make sure Sub.x is a subclass of Super.x, otherwise Sub cannot be used in place of Super.
Workarounds: You can create a custom user model (AUTH_USER_MODEL) which involves quite a bit of code duplication if you only need to change the email field. Alternatively you can leave email as it is and make sure it's required in all forms. This doesn't guarantee database integrity if other applications use it, and doesn't work the other way around (if you want to make username not required).
See https://stackoverflow.com/a/6379556/15690:
class BaseMessage(models.Model):
is_public = models.BooleanField(default=False)
# some more fields...
class Meta:
abstract = True
class Message(BaseMessage):
# some fields...
Message._meta.get_field('is_public').default = True
My solution is as simple as next monkey patching, notice how I changed max_length attribute of name field in LongNamedRestaurant model:
class Place(models.Model):
name = models.CharField(max_length=20)
class LongNamedRestaurant(Place):
food_type = models.CharField(max_length=25)
Place._meta.get_field('name').max_length = 255
Pasted your code into a fresh app, added app to INSTALLED_APPS and ran syncdb:
django.core.exceptions.FieldError: Local field 'name' in class 'LongNamedRestaurant' clashes with field of similar name from base class 'Place'
Looks like Django does not support that.
This supercool piece of code allows you to 'override' fields in abstract parent classes.
def AbstractClassWithoutFieldsNamed(cls, *excl):
"""
Removes unwanted fields from abstract base classes.
Usage::
>>> from oscar.apps.address.abstract_models import AbstractBillingAddress
>>> from koe.meta import AbstractClassWithoutFieldsNamed as without
>>> class BillingAddress(without(AbstractBillingAddress, 'phone_number')):
... pass
"""
if cls._meta.abstract:
remove_fields = [f for f in cls._meta.local_fields if f.name in excl]
for f in remove_fields:
cls._meta.local_fields.remove(f)
return cls
else:
raise Exception("Not an abstract model")
When the fields have been removed from the abstract parent class you are free to redefine them as you need.
This is not my own work. Original code from here: https://gist.github.com/specialunderwear/9d917ddacf3547b646ba
Maybe you could deal with contribute_to_class :
class LongNamedRestaurant(Place):
food_type = models.CharField(max_length=25)
def __init__(self, *args, **kwargs):
super(LongNamedRestaurant, self).__init__(*args, **kwargs)
name = models.CharField(max_length=255)
name.contribute_to_class(self, 'name')
Syncdb works fine. I dont tried this example, in my case I just override a constraint parameter so ... wait & see !
I know it's an old question, but i had a similar problem and found a workaround:
I had the following classes:
class CommonInfo(models.Model):
image = models.ImageField(blank=True, null=True, default="")
class Meta:
abstract = True
class Year(CommonInfo):
year = models.IntegerField()
But I wanted Year's inherited image-field to be required while keeping the image field of the superclass nullable. In the end I used ModelForms to enforce the image at the validation stage:
class YearForm(ModelForm):
class Meta:
model = Year
def clean(self):
if not self.cleaned_data['image'] or len(self.cleaned_data['image'])==0:
raise ValidationError("Please provide an image.")
return self.cleaned_data
admin.py:
class YearAdmin(admin.ModelAdmin):
form = YearForm
It seems this is only applicable for some situations (certainly where you need to enforce stricter rules on the subclass field).
Alternatively you can use the clean_<fieldname>() method instead of clean(), e.g. if a field town would be required to be filled in:
def clean_town(self):
town = self.cleaned_data["town"]
if not town or len(town) == 0:
raise forms.ValidationError("Please enter a town")
return town
You can not override Model fields, but its easily achieved by overriding/specifying clean() method. I had the issue with email field and wanted to make it unique on Model level and did it like this:
def clean(self):
"""
Make sure that email field is unique
"""
if MyUser.objects.filter(email=self.email):
raise ValidationError({'email': _('This email is already in use')})
The error message is then captured by Form field with name "email"