django models design for ride share application, suggestions pls - python

I am working on a ride share application. I need help on designing the models for private messages.
I have designed the below models, its look like complex in querying them in views. can You guys specify a better and easy one.
class Ride(models.Model):
type = models.BooleanField(default=False)
add_source = models.ForeignKey(Address, related_name='source')
add_destination = models.ForeignKey(Address, related_name='destination')
ride_startDateTime = models.DateTimeField(default= datetime.datetime.now, blank=True)
ride_startPref = models.CharField(max_length=10, choices=CHOICES, default='None')
class Conversation(models.Model):
ride_id = models.ForeignKey(Ride)
class Messages(models.Model):
conversation_id = models.ForeignKey(Conversation)
ride_id = models.ForeignKey(Ride)
sender_id = models.ForeignKey(User, related_name='sender')
receiver_id = models.ForeignKey(User, related_name='receiver')
Content = models.TextField(max_length=1000,blank=True)
timestamp = models.DateTimeField(default= datetime.datetime.now, blank=True)
status = models.CharField(max_length=10,blank=True)
User model is django inbuilt.
Please consider the following use cases:
1) A Conversation has to integrate with Ride,
For Ex: User X is a owner of ride 3, User Y can contact X for this ride(3), then the new conversation id(77) will be generated. After that whatever messages sent between them should be under the same conversation id(77).
If another user Z is trying to contact the user X for the same ride 3, then a new conversation ID(33) has to generated.
2) If the user X having another ride called 4, then if user Y contact the User X through the other ride means, it has to generate new conversation id(99) and all the messages sent between them on the ride should come under the same conversation id(99).

Compare with:
class Ride(models.Model):
type = models.BooleanField(default=False)
source_address = models.ForeignKey(Address, related_name='rides_from')
destination_address = models.ForeignKey(Address, related_name='rides_to')
started_at = models.DateTimeField(auto_now_add=True)
start_pref = models.CharField(max_length=10, choices=CHOICES, default='None')
class Conversation(models.Model):
ride = models.ForeignKey(Ride)
user1 = models.ForeignKey(User, related_name='conversations_as_user1')
user2 = models.ForeignKey(User, related_name='conversations_as_user2')
class Message(models.Model):
conversation = models.ForeignKey(Conversation)
posted_by = models.ForeignKey(User, related_name='messages')
content = models.TextField(max_length=1000)
posted_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=10,blank=True)
Keep in mind that whenever wither sender or receiver is deleting a message, it is deleted for both of them.

Related

Filtering unseen messages in Python Django

I have two models, ChatBox and Message. I want to loop through all chats and display them, and I want to display a count of unseen messages (Message model is in a foreign key relation) for each chat.
Could anyone please help me to do this since I ve been strugling with it for few hours.
Firstly I wanted to pass each object from the loop to django filters/tags and add a count of unseen messages to it, but I got advised to use objects.annotation. However, i can not find ways to implement none of these.
Here is my view that displays inbox:
class InboxView(LoginRequiredMixin, ListView):
model = ChatBox
template_name = 'chat/inbox.html'
def get_queryset(self):
# getting all chats for a request.user
object_list = ChatBox.objects.filter(Q(user1=self.request.user) \
| Q(user2=self.request.user)).all()
return object_list
And here are my models:
class ChatBox(models.Model):
user1 = models.ForeignKey(CustomUser,
on_delete=models.CASCADE, related_name='user1')
user2 = models.ForeignKey(CustomUser,
on_delete=models.CASCADE, related_name='user2')
slug = models.SlugField(_("Slug"), max_length=255, unique=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Message(models.Model):
chat = models.ForeignKey(ChatBox, on_delete=models.CASCADE)
sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender')
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
seen = models.BooleanField(default=False)

message_set of Django model

i'm new with Django and as I read the code, I don't understand the message_set attribute of Django model(called Room):
def room(request, pk):
room = Room.objects.get(id=pk)
**room_messages = room.message_set.all()**
participants = room.participants.all()
portion of Models:
class Room(models.Model):
host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
participants = models.ManyToManyField(
User, related_name='participants', blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Message(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
If you define a ForeignKey from Message to Room, Django will add a relation in reverse to the from the Room model to its related Messages. By default this relation is named modelname_set with modelname the name of the origin of the model. You can specify another name by overriding the related_name=… parameter [Django-doc].
If you thus access the relation in reverse, you get all Message objects with room as there room, an equivalent query to room.message_set.all() is thus Message.objects.filter(room=room).

Django Field Error cannot resolve keyword 'is_staff

Cannot resolve keyword 'is_staff' into field. Choices are: dob, experience, id,user, user_id
I get the above error when adding trainer as a Foreign Key to the Subscription model and then accessing any record for Subscription model from admin panel
class Subscription(models.Model):
client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
class TrainerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dob = models.DateField(null=True)
experience = models.PositiveIntegerField(default=0)
You're trying to access an attribute is_staff, which does not exist on the TrainerProfile model. is_staff is an attribute of User, which you reference in your TrainerProfile model's user field.
In order to access this property, you need to "traverse" the relationship from Subscription -> TrainerProfile -> User. Django allows you to do this by using double-underscore notation, like this: some_fk_field__fk_field_attribute.
In your example, you need to change your limit_choices_to option on trainer to traverse the relationship to the user, like so:
class Subscription(models.Model):
client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
on_delete=models.SET_NULL, limit_choices_to={'user__is_staff': True})
plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
class TrainerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dob = models.DateField(null=True)
experience = models.PositiveIntegerField(default=0)
You are referencing the nested relationship in wrong way
class Subscription(models.Model):
# other fields
trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
on_delete=models.SET_NULL,
limit_choices_to={'user__is_staff': True})
That is, it should be user__is_staff instead of is_staff

Foreign key which related to other foreign key choice

I'm trying to make the following models in django:
class Client(models.Model):
client = models.CharField(max_length=200)
loyal = models.BooleanField(default=False)
class Contact(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
client_id = models.ForeignKey(Client, on_delete=models.SET_NULL,null=True)
class Activity(models.Model):
title = models.CharField(max_length=30)
text = models.CharField(max_length=1000)
client_id = models.ForeignKey(Client, on_delete=models.PROTECT)
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
What i want to achieve - when i creating an activity and choose client in it - i want that in contact field i have to choose only from the contacts which related to choosen client, because when i do:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT)
Django allow me to choose from all the contacts. I want to limit somehow the list of contacts from i need to choose, i try this way:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
But i receive this error:
AttributeError: 'ForeignKey' object has no attribute 'contact_set'
How should i do it right?

Django - how to query all users associated with a "listing" object

My models look like this:
CustomUser has a many to many relationship with a "Listing" object
Each Listing object has an "author" field
author = models.ForeignKey(CustomUser)
Essentially, a listing has both an author (CustomUser) and custom users who need confirmation.
I'm trying to get all the custom users who need confirmation for all the listings posted by the author.
I'm not sure what the correct way to query is.
Listing.objects.filter(author=author).needsConfirmation_set.all()
The models
class CustomUser(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=50)
rating = models.FloatField(null=True)
level = models.CharField(max_length=50)
followers = models.ManyToManyField("self", related_name="followers")
following = models.ManyToManyField("self", related_name="following")
interested = models.ManyToManyField('Listing', related_name = 'interested', default=None)
needsConfirmation = models.ManyToManyField('Listing', related_name = 'needsConfirmation', default=None)
confirmed = models.ManyToManyField('Listing', related_name = 'confirmed', default=None)
class Listing(models.Model):
subject = models.CharField(max_length=42)
location = models.CharField(max_length=50, default="N/A")
description = models.CharField(max_length=500)
author = models.ForeignKey(CustomUser)
date = models.DateTimeField(default=timezone.now)
I think it's as simple as:
CustomUser.objects.filter(needsconfirmation__author=author)

Categories

Resources