I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.
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()
This is the full task :
Export a list of customers who completed registration but haven't performed any action (no invoice, expense, withdrawal) last week (3-9 May)
I need to create this type of SQL, but I don't know how to check for actions, what I did for now is
SELECT user FROM users_user
WHERE completed_registration=False
AND date_joined BETWEEN '2021-05-03 00:00:00' AND '2021-05-29 00:00:00'
UNION
SELECT user FROM invoice_invoice;
Check for users who had completed the registration, check for the date, and then check the invoice. But as I check for invoice_invoice itself it's an empty table, why do I get one user when I launch this query? The completed_registration and the date fields which are in queryset right now are only for test.
Only users
This is when I check only for invoices
This is the structure:
Expense model:
class Merchant(BaseModel):
company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='merchants')
name = models.CharField(max_length=255)
company_code = models.CharField(max_length=255, default='', blank=True)
def __str__(self):
return f'{self.company} {self.name}'
class Expense(Operation):
category = models.CharField(choices=ExpenseCategories.get_choices(), default=ExpenseCategories.GENERAL.name,
db_index=True, blank=True, max_length=255)
merchant = models.ForeignKey(Merchant, on_delete=models.PROTECT, related_name='expenses', blank=True, null=True)
amount = models.PositiveIntegerField(default=0, blank=True, help_text='Only taxable amount. In cents')
full_amount = models.PositiveIntegerField(
default=0,
blank=True,
help_text='Full amount. Most of the time same as amount or bigger. In cents'
)
currency = models.ForeignKey(Currency, on_delete=models.PROTECT, related_name='expenses',
default=settings.DEFAULT_CURRENCY_CODE)
description = models.TextField(default='', blank=True)
is_taxable = models.BooleanField(blank=True, default=True)
from_date = models.DateField(null=True, blank=True, help_text='Start date in case of aggregated bulk creation.')
to_date = models.DateField(null=True, blank=True, help_text='End date in case of aggregated bulk creation.')
receipt_number = models.CharField(blank=True, default='', max_length=255, help_text='Number from receipt.')
Invoice model:
class Invoice(Operation):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='invoices')
number = models.CharField(max_length=255)
notes = models.TextField(default='', blank=True)
payment_due = models.DateField()
total = models.PositiveIntegerField(help_text='In cents', default=0)
payment_status = models.CharField(choices=InvoiceStatuses.get_choices(), default=InvoiceStatuses.UNPAID,
max_length=20)
pdf = models.FileField(null=True, blank=True, upload_to='invoices/pdf', max_length=255)
is_sent = models.BooleanField(default=False, help_text="Is pdf invoice sent")
User model:
class User(AbstractUser):
username = None
email = models.EmailField('email address', blank=True)
phone = PhoneNumberField(unique=True)
is_verified = models.BooleanField(default=False)
language = models.ForeignKey(
Language,
default=settings.DEFAULT_LANGUAGE,
on_delete=models.SET_DEFAULT,
)
avatar = models.ImageField(upload_to='users/avatars', null=True, blank=True)
companies = models.ManyToManyField(Company, related_name='users')
active_company = models.OneToOneField(Company, null=True, related_name='active_user', on_delete=models.SET_NULL)
agreement_text = models.TextField(default='', blank=True)
agreement_date = models.DateField(null=True, blank=True)
personal_no = models.CharField(max_length=100, default='', blank=True)
full_name = models.CharField(max_length=255, help_text='Field holds first and last names.', default='', blank=True)
completed_registration = models.BooleanField(default=False)
work_hours_from = models.TimeField(default=settings.DEFAULT_WORK_HOURS_FROM, null=True, blank=True)
work_hours_until = models.TimeField(default=settings.DEFAULT_WORK_HOURS_UNTIL, null=True, blank=True)
You seem to want not exists. I would expect logic like this:
SELECT u.*
FROM users_user u
WHERE u.completed_registration AND
NOT EXISTS (SELECT 1
FROM invoice_invoice i
WHERE i.user = u.user AND
i.invoice_date >= '2021-05-03' AND
i.invoice_date < '2021-05-10'
);
You would repeat this logic for each table where you want to check an action. Also, it is not clear what date you want to use within the invoice table, so I made one up.
I have a Django model "Inspection" which has:
InspectionID (PK)
PartID
SiteID
Date
Comment
Report
Signiture
I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following:
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation.
I want to be able to have a one to many relationship between the inspection ID and date.
You create an extra model, like:
class InspectionDate(models.Model):
inspection = models.ForeignKey(
Inspection,
on_delete=models.CASCADE,
related_name='inspectiondates'
)
date = models.DateField()
You thus can create InspectionDates for a given Inspection.
Or if you want to add extra data, it might be better to define an InspectionGroup model:
class InspectionGroup(models.Model):
pass
class Inspection(models.Model):
id = models.AutoField(primary_key=True, unique=True, db_column='InspectionId')
inspectiongroup = models.ForeignKey(InspectionGroup, on_delete=models.CASCADE, db_column='InspectionGroupId')
part = models.ForeignKey('Part', on_delete=models.CASCADE, db_column='PartId')
site = models.ForeignKey('Site', on_delete=models.CASCADE, db_column='SiteId')
date = models.DateField(db_column='Date')
comment = models.CharField(max_length=255, blank=True, db_column='CommentId')
report = models.FileField(upload_to='docs', null=True, blank=True, db_column='ReportId')
signiture = models.CharField(max_length=255, blank=True, db_column='Signature')
Note: the name of attributes are normally written in snake_case [wiki], not in PerlCase or camelCase.
you may store 'self Foriegnkey' as
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
inspection_id = models.ForeignKey('self', null=True, blank=True)
membership = GroupMembers.objects.filter(profile=profile.id, accepted__isnull=False).values_list('group', flat=True)
When I don't use values_list, I have one element in membership. But I just want to have a list with all the attributes "group" of the GroupMembers models. So I learned about values_list. However, now this will give me an empty list. What is wrong?
EDIT:
class Profile(models.Model):
id = models.AutoField(primary_key=True, db_column='profile_id')
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(blank=True, null=True, default=None, max_length=500)
group_set = models.ManyToManyField(Group, through='GroupMembers')
file_set = models.ManyToManyField(File, blank=True)
user_code = models.TextField(blank=True, null=True, default=None)
class GroupMembers(models.Model):
id = models.AutoField(primary_key=True, db_column='group_profile_id')
group = models.ForeignKey(Group, db_column='group_id')
profile = models.ForeignKey(Profile, db_column='profile_id')
rank = models.CharField(max_length=45, null=True, default=None, blank=True)
invited = models.DateTimeField(auto_now_add=True)
accepted = models.DateTimeField(null=True, default=None, blank=True)
rejected = models.DateTimeField(null=True, default=None, blank=True)
is_admin = models.BooleanField(default=False)
I have following two models
class Questionnaire(models.model)
name = models.CharField(max_length=128, null=True, blank=True)
type = models.CharField(max_length=128,choices=questionnaire_choices)
class TestPopulation(models.Model)
user = models.ForeignKey(User, blank=True, null=True)
age = models.CharField(max_length=20, blank=True, null=True)
education = models.CharField(max_length=50, blank=True, null=True,
choices=EDUCATION_CHOICES)
questionnaire = models.ManyToManyField(Questionnaire, blank=True, null=True)
Now how can i get number of questionnaires for the specific user (logged in user). ?
test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()
questionnaire.objects.filter(test_population__user=user).count()