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
Related
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.
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'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list.
Here are my files and I tried so far.
MODEL.PY
class Employees(models.Model):
# MONTHLY = 'MONTHLY'
# SEMIMONTHLY = 'SEMIMONTHLY'
# BIWKEEKLY = 'BIWKEEKLY'
# WEEKLY = 'WEEKLY'
# DAILY = 'DAILY'
PAY_PERIODS = [
('Monthly', 'Monthly'),
('Bi-weekly', 'Bi-weekly'),
('Weekly', 'Weekly'),
('Daily', 'Daily'),
]
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
is_active = models.BooleanField(default=True, verbose_name='Employee is actives')
first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False)
middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True)
last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False)
full_name = models.CharField(max_length=50, null=True, blank=True)
phone = PhoneField(blank=True, null=True)
email = models.EmailField(max_length=150, blank=True, null=True)
state = USStateField(null=True, blank=True)
street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.')
zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.')
hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True)
hire_date = models.TimeField(auto_now_add=True)
def __str__(self):
return self.full_name
def save( self, *args, **kwargs ):
self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}'
super().save( *args, **kwargs )
class Timesheet(models.Model):
"""A timesheet is used to collet the clock-ins/outs for a particular day
"""
employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
full_name = models.ForeignKey(Employees, on_delete=models.CASCADE, null=True, blank=False, verbose_name='Select YOUR Name')
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True, blank=False)
time_worked = models.DateField(null=True, blank=False)
def __str__(self):
return self.full_name
VIEWS.PY # I tried both function and class based views
class TimesheetView(CreateView):
model = Timesheet
fields = ('full_name', )
# form_class = TimesheetFrom
# queryset = Employees.objects.filter()
# print(queryset)
template_name = 'users/timesheet.html'
success_url = reverse_lazy('timesheet')
#login_required
def timesheet_view(request):
if request.method == 'POST':
form = TimesheetFrom(request.POST)
if form.is_valid():
emp = form.save(commit=False)
emp.user_id = request.user.pk
emp.save()
return redirect('dashboard')
else:
form = TimesheetFrom()
context = {
'form': TimesheetFrom(),
}
return render(request, 'users/timesheet.html', context)
FORM.PY
class TimesheetFrom(forms.Form):
class Meta:
model = Timesheet
fields = '__all__'
exclude = ('employer', )
#This is the current state of the form but I did tried many approaches.
I did search extensively here (Stackoverflow) but no use case for me. Any help will be greatly appreciated with a cup of coffee.
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 need to create double reverse queryset in Django, explained more in the code:
The models
class Book(models.Model):
date = models.DateTimeField(auto_now=True)
book_name = models.CharField(max_length=150)
book_level = models.ForeignKey(Level, on_delete=CASCADE)
book_subject = models.ForeignKey(Subject, on_delete=CASCADE)
book_teacher = models.ForeignKey(Teacher, on_delete=CASCADE, null=True, blank=True)
book_comission = models.DecimalField(max_digits=19, decimal_places=5, null=True, blank=True)
book_black_papers = models.IntegerField()
book_color_papers = models.IntegerField()
book_paper_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_ink_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_color_ink_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_cover_cost = models.DecimalField(max_digits=19, decimal_places=5)
supplier = models.ForeignKey(Supplier, on_delete=CASCADE, null=True, blank=True)
book_total_cost = models.DecimalField(max_digits=19, decimal_places=5)
book_sell_price = models.DecimalField(max_digits=19, decimal_places=5)
viewed_by = models.ManyToManyField(User)
is_double_pages = models.BooleanField(default=False)
is_hidden = models.BooleanField(default=False)
image1 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image2 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image3 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
image4 = ProcessedImageField(upload_to='book_image',
processors=[ResizeToFill(440, 262)],
format='JPEG',
options={'quality': 60}, blank=True, null=True)
published_online = models.BooleanField(default=False)
class VIPSellInvoice(models.Model):
ordered = 'تحت التنفيذ'
delivered = 'منتهية'
canceled = 'ملغاة'
invoice_choices = (
(ordered, 'تحت التنفيذ'),
(delivered, 'منتهية'),
(canceled, 'ملغاة'),
)
date = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=PROTECT)
client = models.ForeignKey(VipClient, on_delete=PROTECT)
total = models.DecimalField(max_digits=19, decimal_places=5, default=0)
status = models.CharField(max_length=160, choices=invoice_choices)
delivery = models.ForeignKey(Delivery, on_delete=PROTECT, null=True, blank=True)
delivery_price = models.DecimalField(max_digits=19, decimal_places=5, default=0, null=True, blank=True)
delivery_notes = models.CharField(max_length=500, null=True, blank=True)
is_done = models.BooleanField(default=False)
class VipPriceList(models.Model):
book_name = models.ForeignKey(Book, on_delete=CASCADE)
book_price = models.DecimalField(max_digits=19, decimal_places=5)
book_client = models.ForeignKey(VipClient, on_delete=CASCADE)
book_client_comission = models.DecimalField(max_digits=19, decimal_places=5)
class VipClient(models.Model):
client_name = models.CharField(max_length=150)
client_address = models.CharField(max_length=150)
client_phone1 = models.CharField(max_length=20)
client_phone2 = models.CharField(max_length=20)
client_note = models.CharField(max_length=500, null=True, blank=True)
client_balance = models.DecimalField(max_digits=19, decimal_places=5, default=0)
client_commission = models.DecimalField(max_digits=19, decimal_places=5, default=0)
Am trying to get the VIPpricelists`` that belong to theclientthat belongs to the currentVip Invoicethen get theBook_set` in the final queryset so that I can deal with it.
here is howw i tried to call it in my views:
def vip_sellinvoice_add_books(request, pk):
current_vip_invoice = get_object_or_404(models.VIPSellInvoice, pk=pk)
test = current_vip_invoice.client.vippricelist_set.all().book_set.all()
context = {
'test': test,
}
return render(request, 'vip/vip_sell_invoice_add_books.html', context)
I get the error:
'QuerySet' object has no attribute 'book_set'
so, is it possible to create such a nested reverse querysets in Django or there is a simpler way to do it?
In that case, you usually query from the Book object itself, like:
Book.objects.filter(vippricelist__book_client__vIPsellinvoice=current_vip_invoice)
So here we query for Books for which there exists a VipPriceList object which has a book_client field that refers to a VipClient that is related to the current_vip_invoice).