I have model name Movie which have many-to-many Relation with Actor Table. Actor Table is further many-to-many relation with Celebrity-Role.
My question is i need only unique values on the base of roles Like Actors who's role is Director they show in Movie Table field with Director and only directors should be there and so on.
i share my models please have a look.
class CelebrityRole(models.Model):
CELEBRITY_CHOICES = (
('Actor', 'Actor'),
('Producer', 'Producer'),
('Writer', 'Writer'),
('Director', 'Director'),
)
role = models.CharField(max_length=8,
choices=CELEBRITY_CHOICES)
def __str__(self):
return self.role
class Actor(models.Model):
GENDER = (
('Male', 'Male'),
('Female', 'Female'),
)
name = models.CharField(max_length=200)
rank = models.CharField(max_length=5, default=0)
gender = models.CharField(max_length=6, choices=GENDER)
avatar = models.ImageField(upload_to='CelebrityGallery/',
blank=True)
description = models.TextField(blank=True)
birth_place = models.CharField(max_length=200, blank=True)
dob = models.DateField(auto_now=False, auto_now_add=False)
height = models.CharField(max_length=20)
is_married = models.BooleanField(default=False)
movies = models.ManyToManyField(
'movies.Movie', related_name='movies', blank=True)
celebrity_role = models.ManyToManyField(CelebrityRole)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Here is my Movie Table
class Movie(models.Model):
title = models.CharField(max_length=200)
year = models.CharField(max_length=25, blank=True)
description = models.TextField(blank=True)
released = models.CharField(max_length=25)
runtime = models.CharField(max_length=25)
language = models.CharField(max_length=255)
country = models.CharField(max_length=100)
metascore = models.CharField(max_length=5, blank=True)
imdb_id = models.CharField(max_length=10, blank=False,
unique=True, default='tt3032400')
imdb_rating = models.CharField(max_length=5, blank=True)
imdb_votes = models.CharField(max_length=100, blank=True)
budget = models.CharField(max_length=25)
box_office = models.CharField(max_length=25, blank=True)
imdb_original = models.BooleanField(default=False)
type = models.CharField(max_length=10, blank=True)
season = models.CharField(max_length=2, default=0,
blank=True)
episode = models.CharField(max_length=3, default=0,
blank=True)
poster_url = models.ImageField(upload_to='Posters/',
blank=True)
video_poster_url =
models.ImageField(upload_to='VideoPosters/', blank=True)
video_url = models.TextField(validators=[URLValidator()],
blank=True, max_length=2000)
genre = models.ManyToManyField(Genre,
related_name='genre_movies')
image_gallery = models.ManyToManyField(ImageGallery,
blank=True)
video_gallery = models.ManyToManyField(VideoGallery,
blank=True)
director = models.ManyToManyField(Actor,
related_name='director')
writer = models.ManyToManyField(Actor,
related_name='writer')
actors = models.ManyToManyField(Actor,
related_name='actors')
producer = models.ManyToManyField(Actor,
related_name='producer')
def __str__(self):
return self.title
I'm not sure how you can do it in your models.py. But you can use the filter method in your views.py when making queries to filter actors whose role is director, etc.
Related
I'm trying to get the object "Book" from prommotion. Book is a ForeignKey in "prommotion", and I filtered all the prommotions that are active. I need to get the "Book" object from the Prommotion if its active and return it.
(And I know promotion is spelled wrong)
Views:
class Book_PrommotionViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Prommotion.objects.filter(active=True)
serializer = PrommotionSerializer(queryset, many=True)
return Response(serializer.data, HTTP_200_OK)
Prommotion Model:
class Prommotion(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
precent = models.DecimalField(decimal_places=2, max_digits=255, null=True, blank=True)
active = models.BooleanField(default=False)
date_from = models.DateField()
date_to = models.DateField()
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'Prommotion'
verbose_name_plural = 'Prommotions'
Book Model:
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=255)
published = models.DateField()
edition = models.CharField(max_length=255)
isbn_code = models.CharField(max_length=255)
pages = models.IntegerField(blank=True, null=True, default=0)
description = models.TextField(null=True, blank=True)
cover = models.CharField(max_length=30, choices=Cover.choices(), default=None, null=True, blank=True)
genre = models.CharField(max_length=30, choices=Genre.choices(), default=None, null=True, blank=True)
language = models.CharField(max_length=30, choices=Language.choices(), default=None, null=True, blank=True)
format = models.CharField(max_length=30, choices=Format.choices(), default=None, null=True, blank=True)
publisher = models.CharField(max_length=30, choices=Publisher.choices(), default=None, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Book'
verbose_name_plural = 'Books'
The first way to get all Books that are related to your active promotions is to extract the book ids from the queryset and pass it to a Book filter
active_promotions = Prommotion.objects.filter(active=True)
Book.objects.filter(id__in=active_promotions.values('book_id'))
Or simply filter books with active promotions by using the double underscore syntax to follow relationships
Book.objects.filter(prommotion__active=True).distinct()
I have a product class in the Django model. Over there are product name, category and department name (foreign key).
So I want to create an automatic code generator that will generate automatically like 2 or 3 alphabets as category name and 3 alphabet department name and 6 digits number; for example: COM-ELC-000001
class Item(models.Model):
item_name = models.CharField(max_length=255, blank =True)
description = models.CharField(max_length=255, blank=True, null=True)
item_choice = (
('IT','IT'),
('Electronics', 'Electronics'),
)
item_type = models.CharField(max_length=255, blank =True, choices = item_choice )
code = models.CharField(unique=True, max_length=255)
unit = models.CharField(max_length=255, blank=True, null=True)
company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True)
department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True)
In Your Models
class Item(models.Model):
item_name = models.CharField(max_length=255, blank =True)
description = models.CharField(max_length=255, blank=True, null=True)
item_choice = (
('IT','IT'),
('Electronics', 'Electronics'),
)
item_type = models.CharField(max_length=255, blank =True, choices = item_choice )
code = models.CharField(unique=True, max_length=255)
unit = models.CharField(max_length=255, blank=True, null=True)
company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True)
department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True)
def save(self, **kwargs):
code = "%s %s" % (self.item_name[:3], self.item_choice)
super(Item, self).save(**kwargs)
How to create table in admin site members without reference
class Mas_Members(models.Model):
ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True)
MemberName = models.CharField(max_length=100)
RegMethod = models.CharField(max_length=10, choices=C_RegMethod)
RegID = models.CharField(max_length=20, blank=True)
DeviceOS = models.CharField(max_length=10, choices=C_DeviceOS)
DeviceID = models.CharField(max_length=30)
NotiID = models.CharField(max_length=30)
ImageFile = models.CharField(max_length=20)
CountryCode = CountryField(blank_label='(select country)')
LangCode = models.CharField(max_length=2)
BirthYear = models.DateField()
Gender = models.CharField(max_length=1, choices=C_Gender)
RegisterDate = models.DateTimeField(editable=False)
CurLatLocation = models.IntegerField(blank=True)
CurLongLocation = models.IntegerField(blank=True)
LastUpdate = models.DateTimeField(default=timezone.now)
I am trying to get user's gender who is in room between start_date and end_date range here is models.py
class Profile(models.Model):
MALE = 'M'
FEMALE = 'F'
GENDER_CHOICES = (
(MALE, u'ere'),
(FEMALE, u'eme')
)
FOOD_TYPE = (
('Veg', 'Vegeterian'),
('Green', 'Green')
)
user = models.OneToOneField(User, related_name="profile", null=True)
firstname = models.CharField(max_length=50, null=True)
lastname = models.CharField(max_length=50, null=True)
phone1 = models.CharField(max_length=50, null=True)
phone2 = models.CharField(max_length=50, null=True, blank=True)
birthdate = models.DateField(blank=True, null=True)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True)
emd_number = models.CharField(max_length=10, null=True)
special_situation = models.IntegerField(choices=SITUATION_CHOICES, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
email = models.EmailField(blank=True, null=True)
city = models.CharField(max_length=20, blank=True)
food_type = models.CharField(max_length=50, choices=FOOD_TYPE, blank=True)
def __unicode__(self):
return self.user.username
class Room(models.Model):
number = models.CharField(max_length=8, null=True)
category = models.ForeignKey(RoomCategory, related_name="rooms")
beds = models.PositiveIntegerField(null=True)
description = models.TextField(blank=True)
size = models.CharField(max_length=2, blank=True)
def __unicode__(self):
return self.number
class Reservation(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
transport_type = models.CharField(max_length=8, blank=True)
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
total_days = models.PositiveIntegerField(null=True, blank=True)
arrival_date = models.DateField(null=True, blank=True)
user = models.ForeignKey(User, related_name="customers")
room = models.ForeignKey(Room, related_name="reservations")
total_payment = models.PositiveIntegerField(null=True, blank=True)
total_paid = models.PositiveIntegerField(null=True, blank=True)
currently i get the rooms by this query below:
queryset = Room.objects.all()
if start_date && end_date:
queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])
how to get user's gender who is in room between dates
You can check like,
for reservetion in Reservation.objects.filter(room__in=queryset):
print reservation.user.gender
#Adaikalaraj how to append user gender in get_queryset method?
class RoomList(ListAPIView):
""" Listing all room """
serializer_class = RoomSerializer
def get_queryset(self):
queryset = Room.objects.all()
start_date = self.request.query_params.get('start_date', None) #date string
end_date = self.request.query_params.get('end_date', None) #date string
if start_date and end_date:
queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date])
return queryset
I am trying to use the "limit_choices_to" functionality in a Django OneToOneField where upstream of what I want to limit the choices on is another ForeignKey. The error I get in the admin with the way I have it set up is:
invalid literal for int() with base 10: 'Storage Array'
I assume this is because it is looking at the actual value in the column asset_type which is an integer foreign key. I need to be able to limit the choices based on a field value of the foreign key as opposed to the key value itself.
Basically what I am trying to accomplish is having the admin area (and other forms) only allow you to choose a valid asset type when adding a new asset. For example, if I am adding a "storage array" the upstream asset tied to it should only be allowed to be asset_type of storage array.
Here is my model:
from django.db import models
from localflavor.us.us_states import STATE_CHOICES
# Table of brand names of assets
class Brand(models.Model):
brand = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.brand
# Table of device types for assets, e.g. "Storage Array"
class Device(models.Model):
device_type = models.CharField(max_length=128, unique=True)
device_url_slug = models.SlugField(max_length=70, unique=True)
class Meta:
verbose_name = "device type"
verbose_name_plural = "device types"
def __unicode__(self):
return self.device_type
# Table of asset locations
class Location(models.Model):
site_name = models.CharField(max_length=128, unique=True)
site_nick = models.CharField(max_length=5, unique=True)
address_line_one = models.CharField(max_length=256)
address_line_two = models.CharField(max_length=256, null=True, blank=True)
address_city = models.CharField(max_length=32)
address_state = models.CharField(max_length=2, choices=STATE_CHOICES, null=True, blank=True)
address_zip = models.CharField(max_length=5)
def __unicode__(self):
return self.site_name
# Table of Environments, e.g. "Production"
class Environment(models.Model):
environment = models.CharField(max_length=128, unique=True)
def __unicode__(self):
return self.environment
class Credentials(models.Model):
AUTH_CHOICES = (
('SSH', 'Standard SSH'),
('SSH-Key', 'SSH with Key-based login'),
('HTTP', 'Standard HTTP'),
('HTTPS', 'Secure HTTP'),
('API', 'API Based'),
('SNMP', 'SNMP Based'),
)
SNMP_VERSIONS = (
('v1', 'SNMP v1'),
('v3', 'SNMP v3'),
)
auth_method = models.CharField(max_length=32, choices=AUTH_CHOICES)
auth_username = models.CharField(max_length=32)
auth_password = models.CharField(max_length=32, null=True, blank=True)
auth_snmp_version = models.CharField(max_length=2, choices=SNMP_VERSIONS, null=True, blank=True)
auth_snmp_community = models.CharField(max_length=128, null=True, blank=True)
class Meta:
verbose_name = "credentials"
verbose_name_plural = "credentials"
def __unicode__(self):
return self.auth_method
class Asset(models.Model):
asset_name = models.CharField(max_length=128, unique=True)
asset_type = models.ForeignKey(Device)
brand = models.ForeignKey(Brand)
model = models.CharField(max_length=128)
serial = models.CharField(max_length=256)
location = models.ForeignKey(Location)
environment = models.ForeignKey(Environment)
datacenter_room = models.CharField(max_length=32, null=True, blank=True)
grid_location = models.CharField(max_length=32, null=True, blank=True)
mgmt_address = models.CharField(max_length=128)
notes = models.TextField(null=True, blank=True)
def __unicode__(self):
return self.asset_name
class StorageArray(models.Model):
OS_NAME_CHOICES = (
('Data OnTap', 'NetApp Data OnTap'),
)
OS_TYPE_CHOICES = (
('7-Mode', 'NetApp 7-Mode'),
('cDOT', 'NetApp Clustered'),
)
HA_TYPE_CHOICES = (
('Standalone', 'Standalone System'),
('HA Pair', 'HA Pair'),
('Clustered', 'Clustered'),
)
asset = models.OneToOneField(Asset, primary_key=True, limit_choices_to={'asset_type': 'Storage Array'})
os_name = models.CharField(max_length=32, choices=OS_NAME_CHOICES, null=True, blank=True)
os_version = models.CharField(max_length=16, null=True, blank=True)
os_type = models.CharField(max_length=16, choices=OS_TYPE_CHOICES, null=True, blank=True)
array_ha_type = models.CharField(max_length=32, choices=HA_TYPE_CHOICES, null=True, blank=True)
array_partner = models.CharField(max_length=128, null=True, blank=True)
credentials = models.ForeignKey(Credentials, null=True, blank=True)
class Meta:
verbose_name = "storage array"
verbose_name_plural = "storage arrays"
def __unicode__(self):
return self.asset.asset_name
class SANSwitch(models.Model):
OS_NAME_CHOICES = (
('FabricOS', 'Brocade FabricOS'),
)
SWITCH_TYPE_CHOICES = (
('Standalone', 'Standalone Switch'),
('Director', 'Director'),
('Router', 'Multiprotocol Router'),
('Blade', 'Blade Chassis IO Module'),
)
SWITCH_ROLE_CHOICES = (
('Core', 'Core'),
('Edge', 'Edge'),
('AG', 'Access Gateway'),
)
asset = models.OneToOneField(Asset, primary_key=True, limit_choices_to={'asset_type': 'SAN Switch'})
os_name = models.CharField(max_length=32, choices=OS_NAME_CHOICES, null=True, blank=True)
os_version = models.CharField(max_length=16, null=True, blank=True)
switch_type = models.CharField(max_length=32, choices=SWITCH_TYPE_CHOICES, null=True, blank=True)
switch_role = models.CharField(max_length=32, choices=SWITCH_ROLE_CHOICES, null=True, blank=True)
credentials = models.ForeignKey(Credentials, null=True, blank=True)
class Meta:
verbose_name = "san switch"
verbose_name_plural = "san switches"
def __unicode__(self):
return self.asset.asset_name
I fixed it all by myself!
It seems to translate further down a relationship you can make use of the double underscore notation that python/django has built in.
To fix my issue:
asset = models.OneToOneField(Asset, primary_key=True, limit_choices_to={'asset_type': 'Storage Array'})
became:
asset = models.OneToOneField(Asset, primary_key=True, limit_choices_to={'asset_type__device_type': 'Storage Array'})