I am trying to query from backward: at fist see my models:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
category = models.ForeignKey('blog.Category', on_delete=models.CASCADE)
def __unicode__(self):
return '%s' % self.title
class Category(models.Model):
name = models.CharField(max_length=100, db_index=True)
I have many category and many post, one category name is tech I am trying to get all the post those are in tech category.
I tried like this. Category.objects.filter(contain__exact='tech') but it is not work anymore.
Can anyone help me to figure get it done?
Best way to get all the post in tech category using foreign key.
tech_blogs = Blog.objects.filter(category__name__icontains='tech')
and also change
category = models.ForeignKey('Category', on_delete=models.CASCADE)
Related
I have a model for applications, which among many attributes have a category. This category is in fact a key to another model that has the category ID, its name, and so on.
class Application(models.Model):
title = models.CharField(max_length=50)
vendor = models.CharField(max_length=50, default="Unknown", null=False)
.
.
.
category = models.ForeignKey('ApplicationCategory', related_name='applications', null=False, default=1, on_delete=models.SET_DEFAULT)
class ApplicationCategory(models.Model):
name = models.CharField(max_length=20, null=False)
description = models.CharField(max_length=200, null=False)
Then, on the Django REST serializers side I have the serializer for the applications:
class SoftwareSerializer(serializers.ModelSerializer):
category = serializers.PrimaryKeyRelatedField(queryset=ApplicationCategory.objects.all())
class Meta:
model = Application
fields = ['id', 'title', ... 'category']
Which is generating the expected API view, with a dropdown for the categories, but showing them as the ApplicationCategory objects and not giving me their name.
API showing Category dropdown with objects instead of names
Is there a way to access attributes of those objects to show the name in the dropdown, for usability sake?
I have also tried creating a CategorySerializer object (class CategorySerializer(serializers.ModelSerializer)) and then using it as category = CategorySerializer(many=False) but instead of dropdowns, I get open text fields for the attributes of the category.
Am I trying to do something that is not expected to work?
try to define the desired text in str method for your ApplicationCategory class:
class ApplicationCategory(models.Model):
name = models.CharField(max_length=20, null=False)
description = models.CharField(max_length=200, null=False)
#example
def __str__(self):
return '%s: %s' % (self.name , self.description)
I need to reference Category and SubCategory models in the Product model. But SubCategory has a ForeignKey to Category. Right now I am referencing as shown below. Is there a better way or is this correct?
class Category(models.Model):
category_name = models.CharField(max_length=250)
def __str__(self):
return f'{self.category_name}'
class SubCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
subcategory_name = models.CharField(max_length=250)
def __str__(self):
return f'{self.subcategory_name}'
class Product(models.Model):
company_category = models.ForeignKey(Category, models.SET_NULL, blank=True, null=True)
company_subcategory = models.ForeignKey(SubCategory, models.SET_NULL, blank=True, null=True)
it depends, can product.company_category be different than product.company_subcategory.category, if the answer is yes then your current setup is correct.
But if those two values will always be the same and you want to keep your tables as normalized as possible, then it might be a good idea to only use company_subcategory.
One caveat to the normalized approach is every time you load an instance of Product and you want to reach product.company_subcategory.category you will generate extra sql queries unless you use the select_related or prefetch_related methods
Product.objects.all().prefetch_related('company_subcategory', 'company_subcategory__category')
Product.objects.select_related('company_subcategory', 'company_subcategory__category').get(pk=1)
I'm trying to figure it out on how I can show only a specific set of dynamic fields in eav to a unique registered model in my apps.models. But I don't know how to this, I've also read the documents but I can't seem to find anything about it, or maybe I've come across it and didn't understand.
Now, what is happening is that, when I add an attribute in the django admin. It also adds the dynamic field in all the models registered in the eav.
What I want to do is that;
model 1 - dynamic_field1, dynamic_field2, dynamic_field3
model 2 - dynamic_field4, dynamic_field5, dynamic_field6
Btw, I'm currently using the django-eav2 the documentation is in the link. I've found my solution for my initial use case here link
Below codes are basically on how to register my models to the eav. Here is my sample models
class ClientName(models.Model):
name = models.CharField(max_length=250, null=True, blank=True)
description = models.TextField(null=True, blank=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return str(self.name)
class CallDetails(models.Model):
client_name = models.ForeignKey(ClientName, on_delete=models.PROTECT, null=True, blank=True, db_index=True)
letter_info = models.TextField(null=True, blank=True)
def __str__(self):
return str(self.client_name)
class Meta:
verbose_name = 'Call Detail'
ordering = ['client_name']
eav.register(ClientName)
eav.register(CallDetails)
below is my admin.py
class CallDetailsAdminForm(BaseDynamicEntityForm):
model = CallDetails
class CallDetailsAdmin(BaseEntityAdmin):
form = CallDetailsAdminForm
admin.site.register(CallDetails, CallDetailsAdmin)
I am building a REST-API that will be consumed by an Angular application - this is for my guitar company’s website. There is an Artist Profile page that display an artist’s name, a short bio and a list of the projects(bands) they’re associated with and the date-ranges they were active with them. Here is where things get complicated.
Any given project can be associated with more than one artist - i.e. I could have two guitar players from the same band. I was able to solve that association by creating a many-to-many field and it worked great…until I realized that I have artists who have been in the same band at different times.
I have tried many approaches so far. I wish I could list them, but I kinda lost track. But, the code below is the where I am at right now. I can indeed associate a band with multiple artists, but I can’t associate different date ranges to different artists in the same bands. Any guidance is much appreciated.
class projectDate(models.Model):
begin = models.DateField()
end = models.DateField()
def __str__(self):
string_date_range = self.begin.strftime("%d/%m/%y") + "-" + self.end.strftime("%d/%m/%y")
return string_date_range
class artistProfiles(models.Model):
artist_name = models.CharField(max_length=20)
artist_image = models.URLField()
description = models.TextField(max_length=500)
band_website = models.URLField()
def __str__(self):
return self.artist_name
class artistProjects(models.Model):
project_name = models.CharField(max_length=20)
dates = models.ManyToManyField(projectDate, related_name='date_span')
artists = models.ManyToManyField(artistProfiles, related_name='projects')
def __str__(self):
return self.project_name
class artistSocialMedia(models.Model):
facebook = models.URLField()
twitter = models.URLField()
instagram = models.URLField()
artist = models.ForeignKey(artistProfiles, related_name='social_media', on_delete=models.CASCADE)
def __str__(self):
return self.artist.artist_name
artistProjects and projectDate should not be a many-to-many relationship, since a projectDate is specific to a project and unlikely to be shared by many. You can instead make artistProjects a foreign key in projectDate so that a artistProjects can have many projectDates but not vice versa:
class projectDate(models.Model):
begin = models.DateField()
end = models.DateField()
project = models.ForeignKey(artistProjects, related_name='dates')
Note that your artistProjects represents just one project, so you should avoid giving it a plural name. Naming it artistProject will make your code more readable.
Not sure whether i can solve your problems or not. I am going to describe it in simple way so you can just adjust it with your models.
These is my advice. Hope it solve your problems.
Artist Profile
id (PK)
artist_name
artist_image
description
band_website
Artist Social Media
id (PK)
artist_profile_id (FK)(Artist Profile)
facebook
twitter
instagram
Artist Project
id (PK)
artist_band_project_id (FK)(Artis Band Project)
Artist Band Project
id (PK)
begin
end
Artist Band Project Member
id (PK)
artis_band_project_id (FK)(Artist Band Project)
artis_profile_id (FK)(Artist Profile)
Regards,
Meikelwis Wijaya
#blhsing Ended up being the closest of all answers, but it took a little more massaging to get the relationships and JSON structure I was looking for.
Here is what worked for the models:
from django.db import models
class artistProfile(models.Model):
artist_name = models.CharField(max_length=20)
artist_image = models.URLField()
description = models.TextField(max_length=500)
band_website = models.URLField()
def __str__(self):
return self.artist_name
class artistProject(models.Model):
project_name = models.CharField(max_length=20)
def __str__(self):
return self.project_name
class projectTenure(models.Model):
begin = models.DateField()
# blank and null are allowed here in case an artists is still with a given project
end = models.DateField(blank=True, null=True)
project = models.ForeignKey(artistProject, on_delete=models.CASCADE)
artist = models.ForeignKey(artistProfile, on_delete=models.CASCADE,
related_name='projects')
def __str__(self):
# TODO: find a way to return the related project and artist names
string_date_range = self.begin.strftime("%d/%m/%y") + "-"
return string_date_range
class artistSocialMedia(models.Model):
facebook = models.URLField()
twitter = models.URLField()
instagram = models.URLField()
artist = models.ForeignKey(artistProfile, related_name='social_media',
on_delete=models.CASCADE)
def __str__(self):
return self.artist.artist_name
And here is how I serialized it:
from rest_framework import serializers
from .models import (artistProfile, artistProject, projectTenure, artistSocialMedia)
class artistSocialMediaSerializer(serializers.ModelSerializer):
class Meta:
model = artistSocialMedia
fields = ('facebook', 'twitter', 'instagram')
class artistProjectSerializer(serializers.ModelSerializer):
class Meta:
model = artistProject
fields = ('project_name',)
class projectTenureSerializer(serializers.ModelSerializer):
project_name = serializers.CharField(source='project.project_name')
class Meta:
model = projectTenure
fields = ('project_name', 'begin', 'end')
class artistProfileSerializer(serializers.ModelSerializer):
projects = projectTenureSerializer(many=True, read_only=True)
social_media = artistSocialMediaSerializer(many=True, read_only=True)
class Meta:
model = artistProfile
fields = ('artist_name', 'artist_image', 'description',
'band_website', 'projects', 'social_media')
I'm kind of new to django. While writing the models for an app I'm doing, I felt like I was doing something wrong because of all the foreign keys I was using for a single model (ticket model to be specific)
My thinking at the beginning was that I wanted each Ticket to keep the information on it's creator, what team this ticket is assigned to and the comments made on the ticket. And other information that don't need foreign keys. Am I doing this right ? I dont know why, but I feel like there is a better way.
class Team(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=2000)
members = models.ManyToManyField(User, through='Team_members')
def __str__(self):
return self.name
class Ticket(models.Model):
name = models.CharField(max_length=200)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
comments = models.ForeignKey(Comment, on_delete=models.CASCADE)
#worker = models.ForeignKey(User, on_delete=models.CASCADE) *to be finished
description = models.CharField(max_length=500)
status = models.BooleanField(default=False)
date_opened = models.DateTimeField('date opened')
date_closed = models.DateTimeField('date closed',null=True, blank=True)
def __str__(self):
return self.name
class Team_member:
team = models.ForeignKey(Team)
user = models.ForeignKey(User)
date = models.DateTimeField('date joined')
class Comment:
text = models.CharField(max_length=2000)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.text
Your question actually has very little (like, nothing?) to do with Django.
Please read about database normalization, it should answer your questions.
Regarding your models, I could notice the following:
Your models look quite good. Don't be afraid of foreign keys, they are the main reason you use a relational database :)
I assume, User might be a member of a Team (service?) or somebody who opens a ticket. If so: when you will have worker foreign key, you most likely won't need team in the Ticket model. It will be redundant, as worker would have a relation to Team.
Nitpicking: Team_member is not pythonic, a PEP8 compliant version would be TeamMember