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'])
Related
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)
I created a magzine model in django. But their are more than three authors of a magzine. I have written below code for three authors. If I write the code of two or three author for a single magzine then it is looks somewhat good. But if I make for more than three authors then it will looks very bad. Now I am confused, Is the method that I have created is wrong? And if it is wrong then how should I write it?
author_name1 = models.CharField(max_length=300, blank=True)
designation1 = models.CharField(max_length=100, blank=True)
author_pic1 = models.ImageField(upload_to="authorpic", blank=True)
author_detail1 = models.TextField(max_length=1000, blank=true)
author_name2 = models.CharField(max_length=300, blank=True)
designation2 = models.CharField(max_length=100, blank=True)
author_pic2 = models.ImageField(upload_to="authorpic", blank=True)
author_detail2 = models.TextField(max_length=1000, blank=true)
author_name3 = models.CharField(max_length=300, blank=True)
designation3 = models.CharField(max_length=100, blank=True)
author_pic3 = models.ImageField(upload_to="authorpic", blank=True)
author_detail3 = models.TextField(max_length=1000, blank=true)
You can make an extra model Author with a ForeignKey [Django-doc] to Magazine. If the same Author can write multiple Magazines, you might want to use a ManyToManyField [Django-doc] instead:
class Author(models.Model):
name = models.CharField(max_length=300, unique=True)
designation = models.CharField(max_length=300, blank=True)
picture = models.ImageField(upload_to_authorpic, blank=True)
detail = model.TextField(max_length=1000, blank=True)
class Magazine(models.Model):
# …
authors = models.ManyToManyField(
Author,
related_name='magazines',
on_delete=models.CASCADE
)
You probably want to make name a unique=True [Django-doc] field to avoid creating two Author objects with the same name.
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?
We have the following example models and are wondering if it's possible to select the foreign keys that match during the same query, possibly as an annotation.
class BaseProduct(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=255)
sub_title = models.CharField(max_length=255, blank=True, null=True)
identifier_retailer = models.CharField(max_length=255)
tags = models.CharField(max_length=255, blank=True, null=True)
has_multiple_variants = models.BooleanField(default=False)
class BaseProductVariant(models.Model):
product = models.ForeignKey(BaseProduct)
name = models.CharField(max_length=128, blank=True, null=True)
sub_title = models.CharField(max_length=255, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
description = models.TextField(blank=True, null=True, help_text='Product description')
features = models.TextField(blank=True, null=True, help_text='One feature per line')
content = RedactorField(allow_image_upload=True, allow_file_upload=True, blank=True, null=True, help_text='Use this for rich HTML on featured products')
warranty_string = models.CharField(max_length=255, blank=True, null=True)
identifier_retailer = models.CharField(max_length=255, blank=True, null=True)
identifier_upc = models.CharField(max_length=255, blank=True, null=True)
identifier_model = models.CharField(max_length=255, blank=True, null=True)
We can query the results easily with BaseProduct.objects.filter()... but would like to select the list of matching BaseProductVariant's at the same time, otherwise we have to query the database in an unconventional fashion, and joining in python with prefetch_related on BaseProductVariant.objects.filter(product__in=[]).prefetch_related(product), select_related works on this too, but it a bit slower due to the extra deserialization on each row.
You can use prefetch_related from BaseProduct to prefetch the variants with the related name. You can also use the Prefetch[1] object from django.db.models to control the attribute name where the prefetched variants end up:
from django.db.models import Prefetch
products_with_variants = BaseProduct.objects.all().prefetch_related(
Prefetch('baseproductvariant_set', to_attr='variants'))
for p in products_with_variants:
print(p.variants)
[1] https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.Prefetch
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.