Multiple related foreignkeys - django

class Flow(models.Model):
name = models.CharField(max_length=200)
pre_requisite = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)
pre_requisite_status = models.ForeignKey("FlowStepStatus",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='pre_requisite_status')
This gives me one pre-requisite and it's status (pre_requisite_status). But I want to have flexibility for multiple pre_requisite and their respective statuses. How can I modify model to have it?

If I understood your requirements correctly - you want a Flow to have more than one pre_requisite and pre_requisite_status. In that case you need to introduce another model (in other words database table) that refers to the Flow model as a foreign key.
class Flow(models.Model):
name = models.CharField(max_length=200)
class PreRequisite(models.Model):
flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='pre_requisites')
pre_requisite = models.ForeignKey(Flow, null=True, on_delete=models.SET_NULL)
pre_requisite_status = models.ForeignKey("FlowStepStatus",
on_delete=models.SET_NULL,
null=True,
blank=True)

Related

django foreign key filtering in admin panel

class City(models.Model):
name = models.CharField(max_length=200, null=True, blank=False)
class District(models.Model):
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200, null=True, blank=False)
class ShippingAddress(models.Model):
city = models.ForeignKey(City, on_delete=models.CASCADE, null=False)
district = models.ForeignKey(District, on_delete=models.CASCADE, null=False)
I would like to filter the admin panel by city (selected city). in order to filter too much similar districts names.
If someone has another way to do it no problem, that was a junior try, waiting for your advice.

How to achieve dependent foreign keys listing in django-admin?

Suppose I have 3 models:- Address, Country, State
Address Model:
class AddressModel(BaseModel):
country = models.ForeignKey(CountryModel, null=True, blank=True, on_delete=models.PROTECT)
state = models.ForeignKey(StateModel, null=True, blank=True, on_delete=models.PROTECT)
city = models.CharField(max_length=200, null=True, blank=True)
pincode = models.CharField(max_length=6, null=True, blank=True)
address_line_1 = models.TextField(max_length=200, null=True, blank=True)
address_line_2 = models.TextField(max_length=200, null=True, blank=True)
Country Model:
class CountryModel(BaseModel):
name = models.CharField(max_length=100)
code = models.CharField(max_length=30)
and State Model:
class StateModel(BaseModel):
country = models.ForeignKey(CountryModel, on_delete=models.PROTECT)
name = models.CharField(max_length=100)
code = models.CharField(max_length=30)
While adding a new address in django admin, I want to show the list of only those states which belong to the selected country i.e I want to implement something like dependent foreign key list in django-admin.
I would like to achieve it without using jquery or ajax
How can I do that?

Django model for different models

I'm learning Django and I'm trying to make a sort of wiki type app. In this wiki there are different type of models: Characters, Items, Spells and Adventures. Each model has some fields that are the same (like name, author, date_created, etc.) and some that are unique to the model, like duration for adventures, alignment for characters, etc. The problem that I have is that if they are different models then every time I want to make something that is common to all of the models (like being able to like, favorite, create, edit, etc.) then I have to code for each model individually. Is there a way of creating a sort of Content model that contains every character, item, spell and adventure so that every time I want to make a form or a function I just make a Content form or Content function?
Here's some of the code, some parts are in spanish but I translated the important parts:
class Character(models.Model):
ALIGNMENT= (
('Legal Bueno', 'Legal Bueno'),
('Legal Neutral', 'Legal Neutral'),
('Legal Malvado', 'Legal Malvado'),
('Neutral Bueno', 'Neutral Bueno'),
('Neutral', 'Neutral'),
('Neutral Malvado', 'Neutral Malvado'),
('Caótico Bueno', 'Caótico Bueno'),
('Caótico Neutral', 'Caótico Neutral'),
('Caótico Malvado', 'Caótico Malvado')
)
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='personajes')
alignment = models.CharField(max_length=50, choices=ALIGNMENT)
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='personaje_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='personaje_favoritos')
class Item(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='items')
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='item_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='item_favoritos')
class Spell(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='hechizos')
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='hechizo_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='hechizo_favoritos')
class Adventure(models.Model):
DURATION = (
('Corta', 'Corta'),
('Mediana', 'Mediana'),
('Larga', 'Larga')
)
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='aventuras')
duration = models.CharField(max_length=50, choices=DURATION)
description = models.CharField(max_length=200)
likes = models.ManyToManyField(Usuario, blank=True, related_name='aventura_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='aventura_favoritos')
I think you can create a base model and then use a OneToOneField to this model in your other models.
class BaseContent(models.Model):
name = models.CharField(max_length=500)
author= models.CharField(max_length=500)
(...)
class Characters(models.Model):
base_content = models.OneToOneField(BaseContent, on_delete=models.CASCADE)
(...)

How to access Many-to-Many relationship from different related models?

I have the following models:
class Instrument(MPTTModel):
name = models.CharField(max_length=100, null=True, blank=True)
class Instrumentation(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
category = models.CharField(max_length=100, null=True, blank=True)
instrument = models.ManyToManyField('Instrument', through='InstrumentMap')
class InstrumentMap(models.Model):
instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT)
instrument = models.ForeignKey(Instrument, verbose_name=_('instrument'), related_name='instrumentmap', null=True, blank=True, on_delete=models.PROTECT)
numbers = models.IntegerField(null=True, blank=True)
class Work_Music(MPTTModel, Work):
instrumentation = models.ForeignKey(Instrumentation, verbose_name=_('instrumentation'), related_name='work', null=True, blank=True, on_delete=models.PROTECT)
How do I get access to all the instruments under an instrumentation object from work?
For example:
piece = Work_Music.objects.get(pk=self.kwargs['pk'])
I tried piece.instrumentation_set.all. That didn't work?
How do you get access from instrumentation?
instrumentation = Instrumentation.objects.get(instrumentation__work=self.kwargs['pk'])
I guess you do a for loop when you can grab the object.
How do you get access from instrumentmap?
InstrumentMap = InstrumentMap.objects.filter(instrumentation__work=self.kwargs['pk']).order_by('order')
Instrumentation is a foreign key, so you must use:
piece = Work_Music.objects.get(pk=self.kwargs['pk'])
piece.instrumentation.instrumentmap.all()
You can use reverse many_to_one relation:
instrumentation = Instrumentation.objects.get(work__id=self.kwargs['pk'])
You can access with:
instrument_maps = InstrumentMap.objects.filter(instrumentation__work__id=self.kwargs['pk'])

How to order_by related field date with annotation?

i have this model :
class Node(MPTTModel):
parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children')
name = models.TextField(blank=True, null=True)
which have this related model :
class Views(models.Model):
related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views')
views_count = models.PositiveIntegerField(null=True, blank=True, default=0)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
view_date = models.DateTimeField(default=timezone.now)
What i am trying to do is to order a queryset of the first model by the view date of the second one, this is the view that i have tried :
last_viewed_trees = Node.objects.filter(tree_type='root').order_by('-related_views__view_date')
In that one the result is correct but i have a duplicate view_date of many users.
I have tried also this one without success :
last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Min('related_views__views_count')
).order_by('-time_of_views')
last_viewed_trees = Node.objects.filter(tree_type='root').annotate(time_of_views= Max('related_views__views_count')
).order_by('-time_of_views')
Nothing have worked for me, there is something that i am missing, but i cannot identify it.