In Django I have 2 models that are inherited from an abstract base class. The base class has an IntegerField that I want to rename and change to DecimalField for some instances. There is a ForeignKey linking the 2 child models. I've read about model inheritance in docs, but there seems to be some constraints. What's the best way to change the IntegerField to DecimalField?
class Parent(models.Model):
intfield = models.IntegerField()
class Meta:
abstract=True
class Child1(Parent):
addedfield = models.CharField(max_length=20)
class Child2(Parent):
addedfield2 = models.DecimalField(max_digits=10, decimal_places=2)
linked = models.ForeignKey(Child1, on_delete=models.CASCADE)
class GrandChild1(Child1):
# change intfield to decimal
class GrandChild2(Child2):
# change intfield to decimal
# linked to GrandChild1 instead of Child1
You can use extra abstract models to alter the fields in the hierarchy:
class Parent(models.Model):
intfield = models.IntegerField()
class Meta:
abstract = True
class DescendantType1(Parent):
"""This is an abstract model that inherits from the Parent model, with the "type 1"
attributes.
"""
addedfield = models.CharField(max_length=20)
class Meta:
abstract = True
class DescendantType2(Parent):
"""This is an abstract model that inherits from the Parent model, with the "type 2"
attributes.
"""
addedfield2 = models.DecimalField(max_digits=10, decimal_places=2)
linked = models.ForeignKey(
"Child1",
on_delete=models.CASCADE,
# This is required on foreign key fields in abstract models.
# See the "Note about foreign key related names" below.
related_name="%(app_label)s_%(class)s_related",
related_query_name="%(app_label)s_%(class)ss",
)
class Meta:
abstract = True
class Child1(DescendantType1):
"""A descendant with "type 1" attributes."""
class Child2(DescendantType2):
"""A descendant with "type 2" attributes."""
class GrandChild1(DescendantType1):
intfield = models.DecimalField(...)
class GrandChild2(DescendantType2):
intfield = models.DecimalField(...)
linked = models.ForeignKey(
"GrandChild1",
on_delete=models.CASCADE,
)
Note about foreign key related names
An abstract model that has a foreign key needs to use a different related_name and related_query_name for each concrete model that inherits from it, otherwise the names for the reverse relationship would be the same for each subclass.
To handle this, django allows you to use template strings with the variables app_label and class so that the names are unique for the child model.
You can find more about this in the documentation.
Related
I have some models, 1 abstract, and 2 that inherit from the abstract model with a ManyToMany relationship. One model gets its members from the other model. I want to implement a constraint on this model so that its members can't be more than the Sum of the remaining_members on the original groups. I created a Q expression that expresses what I want to achieve, but I know it's not the right way to do it. How can I create the constraint with models that are related by a ManyToMany field?
class AbstractGroup(models.Model):
members = models.IntegerField()
class Meta:
abstract=True
class OriginalGroup(AbstractGroup):
remaining_members = models.IntegerField()
new_group_members = ManyToManyField(NewGroup, related_name=new_group, related_query_name=new_group)
class NewGroup(AbstractGroup):
name = models.CharField()
class Meta:
constraints = [
models.CheckConstraint( Q(members__lte=original_groups__sum__remaining_members, name='%(app_label)s_%(class)s_available_members' ) )
]
I have the following models:
class Address(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
....
class Meta:
abstract = True
class BillingAddress(Address):
is_default = models.BooleanField()
...
class Meta:
db_table = 'billing_address'
I'm trying to build a serializer for BillingAddress:
class AddressSerializer(serializers.ModelSerializer):
class Meta:
abstract = True
model = AddressModel
class BillingAddressSerializer(AddressSerializer):
def to_representation(self, obj):
return AddressSerializer(obj, context=self.context).to_representation(obj)
class Meta(AddressSerializer.Meta):
model = UserBillingAddress
fields = (
'id',
'is_default',
)
I keep getting:
ValueError: Cannot use ModelSerializer with Abstract Models.
How can I build my BillingAddressSerializer to reflect both classes?
An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.
Since there is no "Address" table, so "AddressSerializer" would be invalid.
Hello I have two models
class A(models.Model):
slug = models.SlugField()
class Meta:
abstract = True
class B(A):
slug = models.CharField()
class Meta:
abstract = True
I get error AttributeError: Manager isn't available; B is abstract
How do can to redefine attribute in abstract class?
class A cannot be changedю
Abstract models don't have a manager on them because they don't map to a database table. They are used to define reusable mixins that you can compose into concrete models. To make B a concrete model remove the abstract flag and then it will have an objects attribute defined on its instances.
class A(models.Model):
slug = models.SlugField()
class Meta:
abstract = True
class B(A):
slug = models.CharField()
As an aside, as things stand with your models this is a pointless hierarchy because the slug field on B overrides the slug field that is being inherited from A and therefore there is currently zero shared custom functionality between the two definitions. You may as well just have B inherit from models.Model directly.
I'd like to create two similar models AlbumA and AlbumB.
Both of them will have songs.
class AlbumBase(models.Model):
class Meta:
abstract=True
class Song(models.Model):
album = models.ForeignKey(AlbumBase) # problem here
class AlbumA(AlbumBase):
# with specific properties to A (DB fields)
pass
class AlbumB(AlbumBase):
# with specific properties to B (DB fields)
pass
I don't think Song can have foreign key to abstract base class.
How should I model these relationships in django?
EDIT
1. use ManyToManyField
Based on arie's answer, I could define the album-song relationship on the other side, just careful with the names (https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name)
Another difference is that, my original question has 1-Many relationship, and this answer is Many-Many.(I want 1-Many, but could live with M-M..)
class AlbumBase(models.Model):
songs = models.ManyToManyField(Song, related_name="%(app_label)s_%(class)s_related")
class Meta:
abstract=True
class Song(models.Model):
pass
class AlbumA(AlbumBase):
pass
class AlbumB(AlbumBase):
pass
2. multitable-inheritance
Or I could use multitable-inheritance like below.
class Album(models.Model):
pass # not abstract
class Song(models.Model):
album = models.ForeignKey(Album)
class AlbumA(Album):
pass
class AlbumB(Album):
pass
3. Generic foreign Key (based on Mark's answer)
class AlbumBase(models.Model):
class Meta:
abstract=True
class Song(models.Model):
content_type = models.ForeignKey(ContentType, db_index=True, related_name='+')
object_id = models.PositiveIntegerField(db_index=True)
album = generic.GenericForeignKey()
class AlbumA(AlbumBase):
pass
class AlbumB(AlbumBase):
pass
Which one should I go with?
What are the questions that I should ask to pick among these solutions?
If you are deriving your models from an abstract class, its better to add information to these models directly.
you can rather try linking Song class to AlbumA and AlbumB.
Are you really talking about different classes of Albums with distinct properties and database fields?
If you are only concerned about handling songs that differ from album to album, I see no need for an abstract base class and would rather model my models like this:
class Song(models.Model):
title = models.CharField(max_length=100)
...
class Album(models.Model):
title = models.CharField(max_length=100)
songs = models.ManyToManyField(Song)
...
Alternatively, if you are sure that you don't have songs that exist in the context of multiple albums (say compilations or best of-albums) you could also do this:
class Song(models.Model):
title = models.CharField(max_length=100)
album = models.ForeignKey(Album)
...
class Album(models.Model):
title = models.CharField(max_length=100)
...
From what you show and describe don't see any need for GFKs or inheritance.
It's simply a matter of (simple) relations.
I want to set the db_table Meta class attribute in a base class so that all inherited classes will have their names in it, similar to how Django treats related_name model field attribute:
class BaseModel(models.Model):
class Meta:
db_table = 'prefix_%(class)s'
So the inherited model:
class SubModel(BaseModel):
pass
will have db table prefix_submodel.
Is that possible? Can the Meta class access the inheriting class' model name?
No. You can't do that. It is not that simple to have same table to store for multiple classes.
What you need is probably djeneralize project.
From the examples:
class Fruit(BaseGeneralizedModel):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Apple(Fruit):
radius = models.IntegerField()
class Meta:
specialization = 'apple'
class Banana(Fruit):
curvature = models.DecimalField(max_digits=3, decimal_places=2)
class Meta:
specialization = 'banana'
class Clementine(Fruit):
pips = models.BooleanField(default=True)
class Meta:
specialization = 'clementine'
which then allows the following queries to be executed:
>>> Fruit.objects.all() # what we've got at the moment
[<Fruit: Rosy apple>, <Fruit: Bendy banana>, <Fruit: Sweet
clementine>]
>>> Fruit.specializations.all() # the new stuff!
[<Apple: Rosy apple>, <Banana: Bendy banana>, <Clementine: Sweet
clementine>]