I have some problem with order of defining models in django,so i want some thing like this :
class Album(models.Model):
mainTrack = models.OneToOneField(Track)
class Track(models.Model):
albumID = models.ForeignKey(Album)
and in this way when i want run makemigration command,django give this error:
Track is not defined
there is exist any way to solve that??
As you already noticed this line
mainTrack = models.OneToOneField(Track)
references Track but obviously Track is not defined at this time.
Solution:
Reference to the Track model using a string:
mainTrack = models.OneToOneField('Track')
This is also mentioned in the docs:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself.
You should add related_name="track" to your ForeignKey call.
class Album(models.Model):
mainTrack = models.OneToOneField(Track)
class Track(models.Model):
albumID = models.ForeignKey('Album', related_name="track")
Related
I want to create 73 different django models, those models will be very similar, so in theory I would inherit from a base model class and just change the name of the Model/table.
I am aware this is not the best database structure, however I believe this unconventional structure may improve other aspects of my application. The initial point is to test this hypothesis.
How can I have django create the models, without me having to define all 73 of them?
class BaseModel(models.Model):
some_field = models.CharField(max_length=255)
some_other_field = models.CharField(max_length=255)
class Model_NR_01(BaseModel):
pass
...
class Model_NR_73(BaseModel):
pass
Also, in the sample above, I believe the BaseModel would also be created. How could I prevent that, having at the end of the migration only the 73 models mentioned? (If possible, of course).
PS.: I did searched several similar questions, couldn't find an actual answer, only warnings of how bad design it is. I am aware.
The three argument form of type can be used to create classes dynamically. The only thing you need to pass in the attributes dictionary is __module__ as using type this way to create a class will not automatically populate this attribute which is required by Django
class BaseModel(models.Model):
some_field = models.CharField(max_length=255)
some_other_field = models.CharField(max_length=255)
class Meta:
abstract = True
for i in range(1, 74):
model_name = f'Model_NR_{i:02}'
globals()[model_name] = type(model_name, (BaseModel, ), {'__module__': BaseModel.__module__})
I have the following django model:
class Article(models.Model):
filename = models.CharField(max_length=255)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
keys = ['filename', 'collection']
class Meta:
constraints = [
models.UniqueConstraint(
fields=['filename', 'collection'],
name='article_key')
]
As you can see I've defined the same list ['filename', 'collection'] in both the base class and the Meta class. I would like to define it once. I can't define it in Meta because then I get 'Meta got an unrecognised attribute 'keys'. So I must define it in the base class and access it from Meta. I don't know how to share data between the two. I've tried doing:
self.keys
in Meta but that gives 'self is not defined'. I've also tried with just 'keys' but that's also not defined. Any tips? Thanks.
EDIT
Thank you to Willem for pointing out that I can define keys in Meta if I just call it '_keys'. If I do this, however, the question is then how do I access _keys from the base class? I've tried 'meta._keys' and 'Meta._keys'. Both not defined.
EDIT 2
For clarity, the reason that I want 'keys' defined in the base class is that I will (a) be accessing it from properties on the base class, and (b) want to be able to access it from the outside.
You can declare it before the class, then reference it from both the model class and it' Meta:
# making it a tuple since you probably don't want
# it to be mutable
_ARTICLE_KEYS = ('filename', 'collection')
class Article(models.Model):
# making it an implementation attribute since you
# probably don't want to be writeable
# (hint: provide a read-only property for access)
_keys = _ARTICLE_KEYS
class Meta:
constraints = [
models.UniqueConstraint(
fields=_ARTICLE_KEYS,
name='article_key')
]
But this is still ugly IMHO and very probably unecessary - the model's methods should be able to access those values thru self._meta.contraints[0].fields or something similar (don't have models with such constraints at hand right now so I can check how this is actually transformed by the models's metaclass but inspecting self._meta in your django shell should give you the answer).
The methods of a nested class cannot directly access the instance attributes of the outer class.
So, in your case, If you won't use the keys list in the Article class, just defined it once in the Meta class. Otherwise, you need to defined twice!
Consider the following Django model:
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
I would like to define this class from a “static” dict (to be specific in my case it is generated from a file which will not change - so no need to makemigrations and migrate apart from first time).
Here is some pseudo-code to better explain what I want to achieve:
persondict = {‘first_name‘: models.CharField(max_length=255), ‘last_name’: models.CharField(max_length=255)}
class Person(models.Model):
#generate fields from persondict
This is just to start with. Note that you have to change the app_label inside the function, also this will work if you define it inside your models.py where you will use it, otherwise you will need to replace the '__module__' with the appropriate value.
def generate_person_model_from_a_dict(person_model_dict):
class Meta:
app_label = 'your_app_label_here'
person_model_dict.update({
'Meta': Meta,
'__module__': generate_person_model_from_a_dict.__module__,
})
Person = type("Person", (models.Model,), person_model_dict)
return Person
Meta.app_label is needed here to let the Django know which app the newly constructed model should be attached to, e.g. if you are creating it for the app blog and set the model's app_label to blog, then the Django will know, that the app has this model on it (just like you would define it in your blog/models.py)
__module__ is a special attribute of python objects (you can read details about it here https://docs.python.org/3/reference/datamodel.html ) To be brief, it lets Django to know which module your class belongs to, it uses it mostly to display various messages to it's user, see here: https://github.com/django/django/search?utf8=%E2%9C%93&q=module&type=
(just set it to your models.py like in the above example is therefore what Django pretty much expects)
I simplify my code structure, which contains two models:
# created by third part app, not Django one
# but we share same DB, so i have access to this one
class A(models.Model):
title = models.TextField()
# other fields ...
class Meta:
manage = False
class B(models.Model):
model_a = models.OneToOneField(A, related_name='+')
# other fields, to extend model A functionality
Is this a good way to extend third part app model A with my additional fields and methods? Now i have problem to sync this models true one-to-one field. Since I don't have access to trigger model A creation.
In ideal world i should have CarA and CarB. And CarB = CarA relation should be created if CarB exists.
I base this idea on Django 1.5 user extension. Is this clear enough? Or should i do something else?
You could use a property to create the B instance on access if it doesn't exist yet, ie,
class A(models.Model):
title = models.TextField()
# other fields ...
class Meta:
manage = False
#property
def b(self):
if not hasattr(self, "__bcache"):
self.__bcache, created = B.objects.get_or_create(model_a = self)
return self.__bcache
It seems like you're new to both Python and Django so let's explain quickly...
First, the "#property" part: it's a decorator that turns the following function into a computed attribute - IOW you use it as an attribute (myA.b.whatever), and under the hood it turns it into a method call (myA.b().whatever). It's not strictly required here, we would have used an explicit getter (the same method named get_a()) but it's cleaner that way.
Then our method implementation: obviously we don't want to hit the database each time someone looks up A.b, so
first we check if an attribute named __bcache ("b" "cache") is set on the current instance.
if not, we call B.objects.get_or_create(a_model=self) which will either retrieve the existing B instance for this A instance or create one if none exists yet and we store this B instance as self.__bcache so next call will retrieve it directly from __bcache instead of hitting the database.
and finally we return self.__bcache that is now garanteed to exists and point to the related B instance.
I have a Django model that already exists that I'd like to duplicate, and I can't figure out an easy way how because of related-name conflicts across ForeignKeys and ManyToManys.
As an example, let's call the model I currently have Dog:
class Dog(models.Model):
name = models.CharField()
owner = models.ForeignKey('myapp.Owner')
breeds = models.ManyToMany('myapp.Breed', help_text="Remember, animals can be mixed of multiple breeds.")
I'd like to make an exact duplicate of this model for use elsewhere, with a different database table and name. I tried using an abstract base class:
class AnimalAbstract(models.Model):
name = models.CharField()
owner = models.ForeignKey('myapp.Owner')
breeds = models.ManyToMany('myapp.Breed', help_text="Remember, animals can be mixed of multiple breeds.")
class Meta:
abstract = True
class Dog(AnimalAbstract):
pass
class Cat(AnimalAbstract):
pass
This fails because of related_name conflicts.
Is there any way to automatically copy a model like this without explicitly redefining every ForeignKey and ManyToMany?
To preemptively answer questions: yes, I know about multi-table inheritance, and I don't want to use it. I also know that I could simply store this all in the same table and use proxy models with custom managers to automatically filter out the wrong type of animal, but I don't want that either—I want them on separate database tables.
https://docs.djangoproject.com/en/1.8/topics/db/models/#abstract-related-name
To work around this problem, when you are using related_name in an abstract base class (only), part of the name should contain %(app_label)s and %(class)s.
%(class)s is replaced by the lower-cased name of the child class that the field is used in.
%(app_label)s is replaced by the lower-cased name of the app the child class is contained within. Each installed application name must be unique and the model class names within each app must also be unique, therefore the resulting name will end up being different.
Ex:
class Dog(models.Model):
name = models.CharField()
owner = models.ForeignKey(
'myapp.Owner',
related_name="%(app_label)s_%(class)s_dogs")
breeds = models.ManyToMany(
'myapp.Breed',
help_text="Remember, animals can be mixed of multiple breeds.",
related_name="%(app_label)s_%(class)s_dogs")