I'm fairly new to Django and attempting to store a model which will hold transaction information for a purchase between 2 users; a buyer and seller. I therefore want to store 2 UserIDs:
class Transaction(models.Model):
transactionid = models.AutoField(primary_key=True)
# USERID OF SELLER
# USER ID OF BUYER
orderid = models.ForeignKey('Order', db_column='orderid', on_delete=models.SET_NULL, blank=True, null=True)
status = models.CharField(choices=PAYMENT_STATUS, default='pending', max_length=50)
timestamp = models.DateTimeField(auto_now_add=True)
I want to use the following foreign key:
seller = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
however, to my understanding, this will only store the current logged in user which means I wouldn't be able to set both? Is there a better way to do this rather than modifying the model twice (esentially from both accounts)?
Any reccomendations or advice appreciated, thank you!
I hope, in the Transaction model you are going to add the entry if someone made any purchase. Buyer Id you can get from the current user. Seller ID yo can get from the product information.
For adding more than 1 foreign key with the same Model, you can use the related_name parameter.
class Transaction(models.Model):
transactionid = models.AutoField(primary_key=True)
seller = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='seller_name')
buyer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='buyer_name')
Related
I have 3 models (supervisor, students, and allocation)
I am building an allocation system where multiple students can be allocated to one supervisor
Now I want my model to be able to yeld this output
Example of how i want the output to come out
Here are the structure of my model
class StudentProfile(models.Model):
stud_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True)
user_id = models.OneToOneField(User,blank=True, null=True, on_delete=models.CASCADE)
programme_id = models.ForeignKey(Programme, on_delete=models.CASCADE)
session_id = models.ForeignKey(Sessi`**enter code here**`on, on_delete=models.CASCADE)
type_id = models.ForeignKey(StudentType, on_delete=models.CASCADE)
dept_id = models.ForeignKey(Department, on_delete=models.CASCADE)
class SupervisorProfile(models.Model):
super_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True)
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
dept_id = models.ForeignKey(Department, on_delete=models.CASCADE)
class Allocate(models.Model):
allocate_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True)
stud_id = models.ForeignKey(StudentProfile, on_delete=models.CASCADE)
super_id = models.ForeignKey(SupervisorProfile, on_delete=models.CASCADE)
now my main focus is the Allocate model where the allocation is made, and there is a lot of redundancy any suggestions on how to improve my model to remove redundancy in yielding the expected HTML output would be appreciated 🙏
As far as I understand, you need to assign several students to one Supervisor
For this, you only need to use ForeignKey in class StudentProfile
As below:
supervisor=models.ForeignKey(Supervisor,on_delete=models.DO_NOTHING)
But if you need to connect a student to several Supervisor, you should use ManyToManyField
ManyToManyField automatically creates a third table like class Allocate of yourself
For more information, refer to the hire.
It is also possible to reduce the redundancy by considering the department.
However
It doesn't seem that less redundancy can be found in sql database
I hope it was useful
i have a course models and user are allowed to purchase this courses, now i want to filter the courses by the most selling course, i have tried using django agreegate but it seems not to be giving me what i want or maybe i am not doing it the right way.
i have models.py that is storing the courses
class Course(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
course_title = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(unique=True)
course_creayor = models.ForeignKey(User, on_delete=models.CASCADE)
i also have this model that stores the courses that are purchased and enrolled in
class UserCourse(models.Model):
user = models.ForeignKey(User , null = False , on_delete=models.CASCADE)
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
i dont know how to write the view to filter the courses by the most selling
from the image below you can see that learn angular updated is the most selling course for the creator destiny. so how do i filter this for each user, thier most selling course?
You can try annotating the course counts like this:
course_counts = UserCourse.objects.values("course").annotate(count=models.Count("course"))
Then sorting:
sorted_courses = sorted(course_counts, key=lambda x: x['count'],reverse=True)
You will have the sorted_courses[0] containing the highest one and you can retrieve the UUID from the dict
I've got two models that I'd like to perform a reverse search on. I'm wondering how to do this given the fact that one model has to fields with foreign keys to the same model.
class Review(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None)
class Cart(models.Model):
cost = models.DecimalField(max_digits=50, decimal_places=2, null=True, blank=True)
class Job(models.Model):
cart = models.ForeignKey(Cart, related_name="cart_one", on_delete=models.CASCADE, null=True, blank=True)
unscheduled_job = models.ForeignKey(Cart, related_name="cart_two", on_delete=models.CASCADE, null=True, blank=True)
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True)
My query is as follows:
reviews = Review.objects.filter(cart__job__employee=employee)
This query is failing due to the fact that the Job model has two foreign keys that point to the cart model. How would I fix this?
Thanks!
If you specify a related_query_name=… parameter [Django-doc] or a **related_name=… parameter [Django-doc], then that is the name to access the model in reverse, so you can query with:
Review.objects.filter(cart__cart_one__employee=employee)
or if you want to query in reverse with the unscheduled_job, then it is:
Review.objects.filter(cart__cart_two__employee=employee)
You can also combine the two, so bo5th cart anfd unscheduled_job by making use of a Q object:
from django.db.models import Q
Review.objects.filter(Q(cart__cart_one__employee=employee) | Q(cart__cart_two__employee))
You might however want to change the related_name=…s, since this should be the name to access the Job object from the perspective of a Cart model.
Each time i want to add an invoice, i want to have a unique invoice_id which is an increment number (+1), but the problem is that i have a multiple users app, so i get the error that this invoice_id already exist. how can i customize the ids so each user can have its ids following the latest of same user.
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
class Invoice(models.Model):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
invoice_id = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=256)
add an last_invoice field in your company record. Then let it do the work for you by adding a function that generates new invoice:
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=64)
last_invoice = models.CharField(max_length=20)
def get_invoice(self):
l_newNum = self.last_invoice + '1' #your number here
self.last_invoice = l_newNum
self.save()
return l_newNum
class Invoice(models.Model):
company = models.ForeignKey('Company', on_delete=models.CASCADE)
#you no longer need unique as it will create a mess between companies
invoice_id = models.CharField(max_length=20)
name = models.CharField(max_length=256)
def save(self):
self.invoice_id = self.company.get_invoice()
super(Invoice,self).save()
You need to fill in the details here and there, but this should work for you. IDeally I would suggest that the get_invoice is actually used to automatically create Invoice entry for the company, but this would depend on the concrete case you are building.
my buyer field from the Sell model had relationship with the Buyer model like this:
class Buyer(models.Model):
name = models.CharField(max_length=200, blank=True)
description = models.CharField(max_length=200, blank=True)
class Sell(models.Model):
item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
buyer = models.ForeignKey(**Buyer**, related_name='sell', on_delete=models.CASCADE)
But now, it's set to 'User' model as you can see below:
class Sell(models.Model):
item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE)
buyer = models.ForeignKey(**User**, related_name='sell', on_delete=models.CASCADE)
When I go to Django admin, it shows me all the available users from the User model but if I try to save, I got an error like this:
insert or update on table "dma_sell" violates foreign key constraint "dma_sell_buyer_id_4d165f92_fk_dma_buyer_id"
DETAIL: Key (buyer_id)=(13) is not present in table "dma_buyer".
I'm wondering I should NOT have changed this but what is the best way to correct that? I really need to relate the buyer field with User model!
Thank you!
After searching for a long time, I discovered 2 great websites!
Links:
https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html
https://aistlabs.com/switch-foreignkey-one-model-another-and-keep-old-data-migration-pain/
Just recording here for those who can ask in the future!