I have this two models:
class Folder(MPTTModel):
name = models.CharField(max_length=20)
description = models.CharField(max_length=200, null=True, blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
position = models.IntegerField(default=0)
class MPTTMeta:
order_insertion_by = ['position']
class Page(MPTTModel):
title = models.CharField(max_length=50)
file_content = models.TextField()
parent = TreeForeignKey(Folder, null=False, blank=False, related_name='page', on_delete=models.CASCADE)
I have been trying and trying, but I can't find any solution.
Is there anyway to merge those two models in just one tree diagram?
The idea is that a Folder can contain a Folder or a Page
I'm using django 1.6.5 and python3
Maybe you should create an abstract superclass. Then you can have this class from which both (folder and Page) inherit and you can define the parent relation already in there.
Related
I need to model a many to many relationship.
I've read some documentation, but I don't know how to model.
I'll give you an example of what I want to do.
I have two entities, Album and song.
They have a many to many relationship.
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
nombre = models.CharField(unique=True, max_length=255)
songs = models.ManyToManyField(Song, blank=True)
The user in the frontend, provides me the data of an album that I must save.
It provides me the name of the album and the name of the songs.
How could I model it on the serializers?
Nothing runs.
I think you can delete that blank=True i think it automatically can be blank.
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
nombre = models.CharField(unique=True, max_length=255)
songs = models.ManyToManyField(Song, related_name='songs', blank=True)
and you can make the serializer.
Django will create a table for many to many relationships. You can do this by yourself as well with customized fields. For example, you may like to save the order for songs in an album:
class Song(models.Model):
name = models.CharField(unique=True, max_length=255)
class Album(models.Model):
name = models.CharField(unique=True, max_length=255)
class AlbumSong(models.Model):
album = models.ForeignKey('Album', null=False, on_delete=models.PROTECT)
song = models.ForeignKey('Song', null=False, on_delete=models.PROTECT)
order = models.PositiveIntegerField(null=False)
removed = Bit1BooleanField(null=False, default=False)
I have a model called Company. The Company could be the child of a bigger company. So in the model Company should be a attribute "parent" that is also a Company.
I got this:
class Company(models.Model):
name = models.CharField(max_length=250)
parent = models.ForeignKey(
Company,
on_delete=models.SET_NULL,
related_name="notification",
null=True,
blank=False,
)
But django is always saying I need to create a Company class. Is this the right way to do this?
Use 'self' keyword to reference the same model.
class Company(models.Model):
name = models.CharField(max_length=250)
parent = models.ForeignKey(
'self',
on_delete=models.SET_NULL,
related_name="notification",
null=True,
blank=False,
)
I'm creating an article app (in django) where articles can have images. I want to get articles only when they have at least one image. I already tried:
Article.objects.all().annotate(num_extra=Count("Image")).order_by("-num_extra")
But that only returned a sorted queryset starting with the most images and thats not wat I want.
Is there a way to do that?
My models.py
class Article(models.Model):
id = models.CharField(max_length=8, default=None, primary_key=True, blank=True, verbose_name="ID", unique=True, editable=False)
Category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE, verbose_name="Kategorie")
text = models.CharField(max_length=678543)
#And some other fields
class Image(models.Model):
Article = models.ForeignKey(Article, on_delete=models.CASCADE, default=None, verbose_name="Artikel")
authors = models.ManyToManyField(User, verbose_name="Autor", default=None, blank=True)
#And some other fields
You can filter article by which image is not present at Image
Try this:
Article.objects.filter(image__isnull=False)
What I'm trying to achieve is, having model Person that is created and managed by Django have a ManyToMany field with model Property that was "created" using inspectdb and already exists in the database.
(Property contains Geographical data and cannot be managed or changed by Django)
When trying to migrate, it raises :
ValueError: Related model 'cadastroapp.Property' cannot be resolved
Full stack here
Worth nothing that I removed from the migration file the step to create model Property, since it already exists and AFAIK there's no way to tell Django this in the model Class
models.py (simplified) :
class Person(models.Model):
objectid = models.AutoField(primary_key=True)
properties = models.ManyToManyField(
'Property',
through = 'Person_Property',
)
class Meta:
db_table = 'django_person'
class Person_Property(models.Model):
cod_person = models.ForeignKey('Person', on_delete=models.CASCADE)
cod_property = models.ForeignKey('Property', on_delete=models.CASCADE)
class Meta:
db_table = 'django_person_property'
class Property(models.Model):
objectid = models.BigIntegerField(unique=True, primary_key=True)
created_user = models.CharField(max_length=765, blank=True, null=True)
created_date = models.DateTimeField(blank=True, null=True)
last_edited_user = models.CharField(max_length=765, blank=True, null=True)
last_edited_date = models.DateTimeField(blank=True, null=True)
shape = models.TextField(blank=True, null=True) # This field type is a guess. - ESRI Shape
class Meta:
managed = False
db_table = '"GEO"."PROPERTY"'
There are a couple errors in your models.py file.
When defining a Foreignkey or ManytoMany field, you don't want the model name to be in quotes.
Please change:
class Person(models.Model):
properties = models.ManyToManyField(
'Property',
through = 'Person_Property',
)
and
class Person_Property(models.Model):
cod_person = models.ForeignKey('Person', on_delete=models.CASCADE)
cod_property = models.ForeignKey('Property', on_delete=models.CASCADE)
to:
class Person(models.Model):
properties = models.ManyToManyField(
Property,
through = 'Person_Property',
)
and
class Person_Property(models.Model):
cod_person = models.ForeignKey(Person, on_delete=models.CASCADE)
cod_property = models.ForeignKey(Property, on_delete=models.CASCADE)
then delete your migration file cadastroapp.0006_auto_20161122_1533.
then run makemigrations and migrate again.
This may still not migrate without errors, but it will get us on the right track.
I think that you want to put the model name in quotes. In case you leave it without quotes you have to ensure that the model is defined before the ManyToMany field has been defined. So you will need to have first class Property and then class Person in your file. When you put model name as "Property" then you do not need to care about order of class definitions.
I have a project that has 2 different apps. One handles a site's performance metrics and the other estimates site's workload. The workload app has some dependencies on the performance app. However, I am trying to avoid creating a dependency from the metrics app to the workload app in order to better encapsulate the metrics app as stand-alone. For example, metrics has this model:
# models.py in metrics app:
class Site(models.Model):
site_name = models.CharField(max_length=255)
site_geography = models.CharField(max_length=255)
slug = AutoSlugField(populate_from='site_name', unique=True, null=True)
Workload app has objects such as (some omitted for brevity):
# models.py in workload app:
class Resource (models.Model):
name_first = models.CharField(max_length=60)
name_last = models.CharField(max_length=60)
address_street = models.CharField(max_length=80, blank=True)
address_city = models.CharField(max_length=40, blank=True)
address_state = models.CharField(max_length=2, blank=True)
sites = models.ManyToManyField(metrics_models.Site, through='ResourceSiteRelationship', blank=True, related_name='resources')
class Activity (models.Model):
activity_name = models.CharField(max_length=255)
hours = models.DecimalField(max_digits=5, decimal_places=2)
travel = models.BooleanField()
description = models.TextField(blank=True)
class ResourceSiteRelationship (models.Model):
roles = models.ManyToManyField(Role, blank=True, related_name='resource_site_relationships')
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships')
site = models.ForeignKey(metrics_models.Site, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships')
Site should also have the following field relationship:
activities = models.ManyToManyField(Activity, related_name='sites', blank=True)
Is it best to add that field to the metric's app's instance of Site? Is it better to create a one-to-one class for Site in the workload app and extend like so:
class Site(models.Model):
site = models.OneToOneField(metrics_models.Site, on_delete=models.CASCADE)
activities = models.ManyToManyField(Activity, related_name='sites', blank=True)
Or is there another way to do this?