I'm trying to create a Django ORM mapping that's compatible with an existing data model, so I'm trying to work with an existing set of table and column names.
I've got a multi-table inheritance situation where a class InformationObject derives from class Object. I'd like to let Django handle this the usual way:
class Object(models.Model):
class Meta:
db_table = "object"
class InformationObject(Object):
class Meta:
db_table = "information_object"
In this case Django would automatically create a one-to-one field on the inheriting model called object_ptr_id. However, on the schema I'm constrained to use, the reference to the Object is simply called "id". So:
Is there a way to somehow specify the name of the column Django auto-magically uses for multi-table inheritance?
The alternative, which I'll have to use otherwise, is to use an explicit one-to-one field, but then I won't be able to inherit non-database methods from the Object model:
class Object(models.Model):
class Meta:
db_table = "object"
class InformationObject(models.Model):
class Meta:
db_table = "information_object"
id = models.OneToOneField(Object, primary_key=True, db_column="id")
Any ideas? Maybe I could create a common base class for both of them and put non-db methods there...?
From the django docs (development version):
As mentioned, Django will automatically create a OneToOneField linking your child class back any non-abstract parent models. If you want to control the name of the attribute linking back to the parent, you can create your own OneToOneField and set parent_link=True to indicate that your field is the link back to the parent class.
As mentioned by #fusion quoting from the docs, you will have to create a OneToOneField if you want to specify the column, while using model inheritance. The inherited fields will be available in the child class in both self scope AND the one-to-one field.
class Object(models.Model):
class Meta:
db_table = "object"
column_1 = models.CharField()
class InformationObject(Object):
class Meta:
db_table = "information_object"
# arbitrary property name (parent_link)
parent_link = models.OneToOneField(Object, primary_key=True, db_column="id", parent_link=True)
In this example:
>>> inf_obj = InformationObject.objects.get(pk=1)
>>> print inf_obj.column_1 == inf_obj.parent_link.column_1
True
Related
So I'm struggling with ordering the choices within an InlinePanel (for an orderable) on my site. In the admin page, when adding a new item, the options are presented in the order they were added to the site (so, essentially the 'id' for that item); this is less than ideal considering there are hundreds of options presented in a manner that is not user friendly.
I'm assuming this needs to be defined as ordering meta within the orderable, but I can't seem to get it to work. This is what my orderable looks like:
class RelatedPeople(Orderable):
service = ParentalKey('service.Services', related_name='related_person')
person = models.ForeignKey('person.People', null=True, on_delete=models.SET_NULL, related_name='related_service')
panels = [
FieldPanel('person')
]
I've tried the following with no success:
class Meta:
ordering = 'person'
and, trying to append the field within 'person' that I want to sort by, 'name':
class Meta:
ordering = 'person.name'
There must be an obvious way to solve this that I'm over looking. A default sort order of the 'id' (in this case, for 'person.People') is rarely ever going to be suitable from the perspective of the content creator.
Any advice would be greatly appreciated!
Thanks in advance,
Rob
Person model should have:
ordering = ['name']
instead of
ordering = 'name'
And your Orderable object should have it's meta changed to
class Meta(Orderable.Meta):
Via Django Docs, this is the example of abstract base classes, and ordering:
Meta and multi-table inheritance¶
In the multi-table inheritance situation, it doesn’t make sense for a
child class to inherit from its parent’s Meta class. All the Meta
options have already been applied to the parent class and applying
them again would normally only lead to contradictory behavior (this is
in contrast with the abstract base class case, where the base class
doesn’t exist in its own right).
So a child model does not have access to its parent’s Meta class.
However, there are a few limited cases where the child inherits
behavior from the parent: if the child does not specify an ordering
attribute or a get_latest_by attribute, it will inherit these from its
parent.
If the parent has an ordering and you don’t want the child to have any
natural ordering, you can explicitly disable it:
class ChildModel(ParentModel):
# ...
class Meta:
# Remove parent's ordering effect
ordering = []
When an abstract base class is created, Django makes any Meta inner
class you declared in the base class available as an attribute. If a
child class does not declare its own Meta class, it will inherit the
parent’s Meta. If the child wants to extend the parent’s Meta class,
it can subclass it. For example:
from django.db import models
class CommonInfo(models.Model):
# ...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
# ...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
I am not familiar with Wagtail, but can you take a look at this issue :
https://github.com/wagtail/wagtail/issues/4477#issuecomment-382277375
Update:
Maybe you just need to update your Person model like this:
class Person(models.Model):
...
class Meta:
ordering = 'name'
In your files, you try to order RelatedPeople by Person, but what you need is to order the Person list by name in your wagtail dropdown
I.e. we have SomeSeries with several SomeDecors, where ForeignKey of SomeDecor points to SomeSeries. I want both to be abstract and later instantiate several pairs of it (with it's own tables in db). Is it possible?
I.e.
class SomeSeries(models.Model):
class Meta:
abstract = True
vendor = models.ForeignKey(Vendor)
name = models.CharField(max_length=255, default='')
def __unicode__(self):
return "{} {}".format(self.vendor, self.name)
class SomeDecor(WithFileFields):
class Meta:
abstract = True
series = models.ForeignKey(SomeSeries) # some magic here to make ForeignKey to abstract model
texture = models.ImageField()
# -------------------------------------------
class PlinthSeries(SomeSeries): pass
class PlinthDecor(SomeDecor): pass
# Some magic to make PlinthDecor.series points to PlinthSeries
EDIT
Actually I don't want complicity of polymorphic relations, I want pure abstract models just to save typing (what abstract models are initially for). Suppose in my case the simplest way is to exclude ForeignKey from base model and type it only in all inherited models:
class SomeSeries(models.Model):
class Meta:
abstract = True
#...
class SomeDecor(WithFileFields):
class Meta:
abstract = True
series = None #?
#..
texture = models.ImageField()
def do_anything_with_series(self): pass
class PlinthSeries(SomeSeries): pass
class PlinthDecor(SomeDecor): pass
series = models.ForeignKey(PlinthSeries)
You can't create ForeignKey referencing abstract model. It's, even, doesn't make any sense, because ForeignKey translates into Foreign Key Constraint which have to reference existing table.
As a workaround, you can create GenericForeignKey field.
You can not do it because if you create two class inherit from your abstract class to what class your foreignkey should do? for first or for second?
So you need to create GenericForeignKey or not do any field and only after create model inherits from your abstract model add your foreign key.
I have the following model parent
class ModelParent(PolymorphicModel):
company = models.CharField(max_length=50)
.......
and the model child
class ModelChild(ModelParent)
company = models.CharField(max_length=10, blank=True)
...........
how can I make the model child company attribute overwrite the parent company model attribute without making the abstract parent model
This is not possible without an abstract parent model, unfortunately.
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 isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class.
This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None.
A recommendation instead would be to simply create a property or rename the child model's field. Another thing you could do is remove the parent model's "company" field and move it to all of the children models instead.
class ModelChild(ModelParent)
child_company = models.CharField(max_length=10, blank=True)
...........
I am trying to design an abstract model that contains a field. Subclassed models will have this field, but they will be of various field types.
Example
class AbsModel(models.Model):
data = models.??? #I want subclasses to choose this
def __unicode__(self):
return data.__str__()
class Meta:
abstract = True
class TimeModel(AbsModel):
data = models.TimeField()
...
class CharModel(AbsModel):
data = models.CharField(...)
...
I am looking for a way to enforce the existence of the data field so I can write unicode once for all objects.
If this isn't possible, how can I refer to the "data" field of the subclass when calling the super class's unicode
I have a feeling this second question has an obvious answer I am missing.
It's not possible to override a superclass field where the field is of type models.Field.
https://docs.djangoproject.com/en/1.4/topics/db/models/#field-name-hiding-is-not-permitted
You can get round this by defining a field of another type in the superclass, and then overriding it in the child (perhaps include a __str__() method just in case the data field isn't overriden).
from django.db import models
class AbsDataField:
def __str__(self):
return "undefined"
class AbsModel(models.Model):
data = AbsDataField
def __unicode__(self):
return self.data.__str__()
class Meta:
abstract = True
class TimeModel(AbsModel):
data = models.TimeField()
#...
class CharModel(AbsModel):
data = models.CharField(max_length=32)
#...
You can write something like that:
class AbsModel(models.Model):
def __unicode__(self):
if hasattr(self, "data") and isinstance(self.data, models.Field):
return data.__str__()
return u"Unknown"
You cannot do that in Django:
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.
Overriding fields in a parent model leads to difficulties in areas
such as initializing new instances (specifying which field is being
initialized in Model.__init__) and serialization. These are features
which normal Python class inheritance doesn't have to deal with in
quite the same way, so the difference between Django model inheritance
and Python class inheritance isn't arbitrary.
[...]
Django will raise a FieldError if you override any model field in any
ancestor model.
Given the following models:(don't mind the TextFields there're just for illustration)
class Base(models.Model):
field1 = models.TextField()
class Meta:
abstract=True
class Child1(Base):
child1_field = models.TextField()
class Child2(Base):
child2_field = models.TextField()
class Content(models.Model):
aso_items = models.ManyToManyField('Base')
According to these definitions a Content object can be associated with more than one Base object, eg. an interview(=Content object) can be linked with a musician(=Child1 object), a filmdirector(=Child2), etc.
Now, for my question:
Is it possible to filter Content objects according to which model the aso_items field points to?
An example : Say I would like a Queryset containing all the Content objects that are associated with a specific object of Child1(eg. all the interviews associated with the musician Bob Dylan), how can I achieve this?
Further, what if I'd want a QuerySet containing all the Content objects that are associated with Child1 objects?(eg. all the interviews that associated with musicians)
How does this change the filtering?
Thanks in advance
ps: I'm experiencing some problems with white space in the preview, forgive me
You should check the section of the Django docs regarding using related_name for abstract base classes. http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
To quote the docs:
If you are using the related_name
attribute on a ForeignKey or
ManyToManyField, you must always
specify a unique reverse name for the
field. This would normally cause a
problem in abstract base classes,
since the fields on this class are
included into each of the child
classes, with exactly the same values
for the attributes (including
related_name) each time.
To work around this problem, when you
are using related_name in an abstract
base class (only), part of the name
should be the string %(class)s. This
is replaced by the lower-cased name of
the child class that the field is used
in. Since each class has a different
name, each related name will end up
being different.
Using this information I would recommend moving the m2m field into the Base class:
class Content(models.Model):
# Add remaining fields for Content
pass
class Base(models.Model):
field1 = models.TextField()
items = models.ManyToManyField(Content,related_name="%(class)s_related")
class Meta:
abstract=True
class Child1(Base):
child1_field = models.TextField()
class Child2(Base):
child2_field = models.TextField()
Apparently a ForeignKey relation(or ManyToMany for that matter) with a abstract class isn't allowed.
I get the following error : 'AssertionError: ForeignKey cannot define a relation with abstract class Artiest'.
A possible solution is to define the base class as non-abstract, however this implies that one could instantiate models of the base class. Which isn't the behavior I want.(after all it was an abstract class)
Has someone come accross the same problem how did you solve it? Any alternatives?
Have a look at http://www.djangoproject.com/documentation/models/generic_relations/ which goes through generic relations. Your Content model would match up to their TaggedItem model, and your Base model would match up to their Animal/Vegetable/Mineral model (with Child1 and Child2 extending).
Getting all of the Content objects for a single child would be (assuming you set the GenericRelation to contents inside Base):
child_contents = childObject.contents.all()
And to get all Content objects for a model:
ctype = ContentType.objects.get_for_model(Child1)
all_child_contents = Content.objects.filter(content_type=ctype)