Django ManyToMany CheckConstraint IntegerField - django

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' ) )
]

Related

Django change IntegerField to DecimalField on inherited model

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.

Serialize Model from Derived (Abstract) Model

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.

Django model + Unique column on two tables (inheritance)

How to create constraint (on database to keep integrity) base on columns from child and parent table?
Model:
class DBMaster(models.Model):
col1 = models.CharField()
class DBOne(DBMaster):
col_own....
col1 - should be this same how in DBMaster
class Meta:
constraints = [
models.UniqueConstraint(fields=['col_own', 'col1'], name='CON_UNIQUE_1')
]
We can use materialized view but we wont.
Any sugestions?
I think you should use unique_together in your model and your base model should be abstract
class BaseDBMaster(models.Model):
col1 = models.CharField()
class Meta:
abstract = True
class DBMaster(BaseDBMaster):
pass
class DBOne(BaseDBMaster):
col_own....
col1 - should be this same how in DBMaster
class Meta:
unique_together = ('col1', 'col_own')

Django modeling, common base and one-to-many relationship

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.

How to have abstract model with unique_together?

Why I am getting:
Error: One or more models did not validate:
test.test: "unique_together" refers to slug. This is not
in the same model as the unique_together statement.
test.test: "unique_together" refers to version. This is not
in the same model as the unique_together statement.
I have such model definition:
class SlugVersion(models.Model):
class Meta:
abstract = True
unique_together = (('slug', 'version'),)
slug = models.CharField(db_index=True, max_length=10, editable=False)
version = models.IntegerField(db_index=True, editable=False)
class Base(SlugVersion):
name = models.CharField(max_length=10)
class Test(Base):
test = models.IntegerField()
I have Django 1.3.
It seems it is a bug in Django.
It's because Test is inheriting from Base using multi-table inheritance, which creates separate tables for the two models and links them with a OneToOne relationship. So the slug and version fields exist only in the Base table but not in the Test table.
Do you need Base to be non-abstract? In other words, will you create any actual Base objects? If you set it to be abstract, this error goes away.