Django model relations access - python-3.x

Are there any easy way of accessing all the article comments when I have setup my models like this? If this is not the correct way of doing it, please let me know a better way to create a relationship.
My model,
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Article(models.Model):
author = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
class Comment(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=True)
comment = models.CharField(max_length=450, blank=False, null=True)
def __str__(self):
return f"{self.comment}"
Are there any easy query to access the comment when looping the article? Or is this the wrong way of setting up relations?

Related

Update django model database with ForeignKey by using serializer

I have created a django model which includes a foreign key to a user as follows:
from authentication.models import User
from django.db import models
class Event(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
dr_notice_period = models.IntegerField(blank=True, null=True)
dr_duration = models.IntegerField(blank=True, null=True)
dr_request = models.FloatField(blank=True, null=True)
My serializers.py file is as follows:
class EventSerializer(serializers.ModelSerializer):
user = UserSerializer(many=True, read_only=True)
class Meta:
model = Event
fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request']
What I need to do is to go to a url and with a POST request to upload the data to the database, but without specifically specifying the user.
My views.py is as follows:
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from vpp_optimization.serializers import EventSerializer
#api_view(['POST'])
def event(request):
serializer = EventSerializer(data=request.data)
if serializer.is_valid():
instance = serializer.save(commit=False)
instance.user = request.user
instance.save()
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
else:
return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
As I study I thought that by using commit=False in save would solve the problem, but I am getting the following error:
'commit' is not a valid keyword argument to the 'save()' method. If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. You can also pass additional keyword arguments to 'save()' if you need to set extra attributes on the saved model instance. For example: 'serializer.save(owner=request.user)'.'
Is there a better way to do what I intent to do?
You pass the user as parameter, so:
if serializer.is_valid():
instance = serializer.save(user=request.user)
return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK)
Note: It is normally better to make use of the settings.AUTH_USER_MODELĀ [Django-doc] to refer to the user model, than to use the User modelĀ [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

How to join two tables in django and serialize the same using one serializer?

I have been learning django and django rest framework since couple of weeks and I want to figure out how can I join two tables and serialize the data of same to return the json response using django rest framework.
I want to return result as json response:
{ 'user_id_id': 1, 'request_msg': 'Hi', 'response_msg': "Hi, Welcome" }
where result is
from django.db import connection
cursor = connection.cursor()
con = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
Here is what I have tried :
#backend/Models.py
class User(models.Model):
username = models.CharField(max_length=50)
name = models.CharField(max_length=50, blank=True, null=True)
uid = models.CharField(max_length=12, blank=True, null=True)
age = models.CharField(max_length=3, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
default_related_name = 'users'
def __str__(self):
return self.name
class Request_Messages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class Response_Messages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'response_messages'
def __str__(self):
return self.response_msg
#backend/serializers.py
class ListSerializer (serializers.Serializer):
user_id_id = serializers.IntegerField()
request_msg = serializers.CharField(max_length=100)
# request_msg_created_at = serializers.DateTimeField(read_only=True)
response_msg = serializers.CharField()
# response_msg_created_at = serializers.DateTimeField(read_only=True)
#backend/views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Response_Messages, Request_Messages, User
from .serializers import ListSerializer
from django.db import connection
#api_view(['GET', 'POST'])
def chatbot(request):
if request.method == 'GET':
cursor = connection.cursor()
query_set = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
columns = [column[0] for column in query_set.description]
results = []
for row in query_set.fetchall():
results.append(dict(zip(columns, row)))
serializer = ListSerializer(results)
return Response(serializer.data)
About serializers, You should refer to the docs (they're awesome and explain it best).
To give you a direction, I like to create a serializer for every model and if it's related to another model, I refer that in serializer, that way, You can easily customize behavior for each model (although not the only way at all).
So, about serializing I would do the following (notice my comments as well):
from django.contrib.auth.models import User
class User(User):
# Your user class, except, it should inherit Django's User/AbstractUser class.
class RequestMessages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='requests_msg')
# NOTICE THE NEW RELATED NAME, WE'LL USE IT LATER.
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class ResponseMessages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='responses_msg')
def __str__(self):
return self.response_msg
class RequestMsgSerializer(serializers.ModelSerializer):
# Specify what ever you like...
class Meta:
model = RequestMessages
fields = # Whatever you like to serialize.
class ResponseMsgSerializer(serializers.ModelSerializer):
class Meta:
model = ResponseMessages
fields = # Whatever you want serialized.
class UserSerializer(serializers.ModelSerializer):
# Using required = False will cause that every time you create a user they don't have to own messages.
requests_msg = RequestMsgSerializer(many=False, required=False)
responses_msg = ResponseMsgSerializer(many=False, required=False)
class Meta:
model = User
field = # Same as above ..
About your query, using raw SQL in Django is rear, usually, in most cases the Django built-in ORM will do the job and usually faster and better than you.
In your case, if you'll call your query like this for exmaple:
query_set = User.objects.filter(user=request.user)
the QuerySet object created will hit the DB one for the user object and X queries for all the associated messages with said user, so expensive.
But no need for a custom query with joins and stuff like that, Django has prefetch_related and select_related.
exmaple:
query_set = User.objects.filter(user=request.user).prefetch_related('requests_msg')
will reduce all the queries made for request messages associated to a user to only one!
Recap:
I wrote a lot because I'm still learning this stuff myself self and if you teach others you got it!
Refer to DRF's docs about serializers (there's even a dedicated section for nested serializers) and API Views, they really great.
Refer to Django's docs about prefetch related, select related and queries in general, again, Amazing docs that cover everything.
Don't just copy my code or anyone else's, there's no problem with that, just make sure you understand it first if not, you're bound to get stuck with it again!

Adding comment feature in Django DetailView?

What the simplest logic i can add in class HotelDetailView(DetailView) so users can comment on a particular hotel detail page. And it capture user too.
models.py
class Hotel(models.Model):
name = models.CharField(max_length=150)
owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
image = models.ImageField(upload_to=upload_location, null=True, blank=True)
class CommentOnHotel(models.Model):
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=200)
published = models.DateField(auto_now_add=True)
def __str__(self):
return '{} - {}'.format(self.hotel.name, self.user.email)
Forms.py
class CommentOnHotelForm(forms.ModelForm):
class Meta:
model = CommentOnHotel
fields = ['content']
views.py
class HotelDetailView(DetailView):
model = Hotel
........
actually i gave you the better approach for that, but if you want to make all logic and functions at DetailView which is not recommended, here is the solution, you need to override POST function of DetaiView:
class HotelDetailView(DetailView):
model = Hotel
def post(self, request, *args, **kwargs):
# get the hotel object
hotel = self.get_object()
#check for validation of form
form = CommentOnHotelForm({
"hotel": hotel,
"user" :request.user
"comment": request.POST.comment
})
if form.is_valid():
form.save()
#choose where you want to redirect

NOT NULL constraint failed: product_product.author_id

When I am going to post objects in the postman I am getting this error
NOT NULL constraint failed: product_product.author_id
I included Basic Auth in the Authorization section anyway it gives me error.
models.py
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
brand = models.CharField(max_length=200)
rating = models.PositiveSmallIntegerField(default=0)
description = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
serializers.py
class ProductSerializer(serializers.HyperlinkedModelSerializer):
category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name')
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Product
fields = ['id', 'url', 'category', 'name', 'brand', 'rating', 'description', 'price']
Why Not Null constraint happens? how can I solve this? Thanks in advance!
I think you should add models.create_all() in Models.py to create the database
The error happens simply because your create request is not providing a value for
author attribute of a product.
# models.py
class Product(models.Model):
....
author = models.ForeignKey(User, on_delete=models.CASCADE)
so in order to resolve this issue totally depends on your business logic,
Is it important for a product to have an Author?
[NO] ==> then just make the foreign key null=True, blank=True
[YES] ==> Then you need to modify your creation logic a lil bit.
Is the author of a product is the same one who created it?
[YES], then this can easily be done by overriding your serializer's create method
....
# Inside you serializer
def create(self, validated_data):
validated_data['author'] = self.context['request'].user
return super().create(validated_data)
[NO], You have to make the serializer accept writes on author field.
A small note, your ProductSerializer Meta class's fields attribute, doesn't include 'author', make sure it is added there too.

stream - Follow activity is shown in news feed

I have created the following feeds:
notification, timeline_aggregated, user, and timeline.
In my application, users can create posts and follow other users. Users view the posts from people that they follow. However, when I retrieve an individual user's news feed, follow actions are included along with post actions. I've spent a lot of time attempting to figure out why this is. Possibly I am missing something?
Thanks.
class AppBaseModel(models.Model):
created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
abstract = True
class UserFollow(AppBaseModel, Activity):
class Meta:
verbose_name = 'UserFollow'
verbose_name_plural = 'UserFollows'
user = models.ForeignKey(API_USER_MODEL, on_delete=models.CASCADE, related_name='following_set')
target_user = models.ForeignKey(API_USER_MODEL, on_delete=models.CASCADE, related_name='follower_set')
#property
def activity_actor_attr(self):
return self.user
#property
def activity_notify(self):
return [feed_manager.get_notification_feed(self.target_user.id)]
#property
def extra_activity_data(self):
return {'user': self.user.id,
'target_user': self.target_user,
'created_at': self.created_at}
#classmethod
def activity_related_models(cls):
return ['user', 'target_user']
You're inheriting the Activity model when you create your UserFollow class, it will create 'follow' activities and push them into the stream as well.
https://github.com/GetStream/stream-django#model-integration
"Simply mix in the Activity class on the models you want to publish."

Resources