How to show foreign key in queryset django - django

I have 1 question.
These are my django models.(This is just example)
class Users(models.Model):
username = models.Charfield()
class CommunityBoard(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=30)
contents = models.TextField()
I send data(nsdictionary format) to server using post
{ pk = 1 }
in views.py
def detailCommuBoard(request):
returnValues = {}
returnValues.update(csrf(request))
pk = request.POST['pk'];
detailContents = CommunityBoard.objects.filter(pk=pk)
returnValues = serializers.serialize('json', detailContents)
return HttpResponse(returnValues)
then, I got serialized data in iphone.(json format)
{
fields = {
contents = "\Uc5ed\Uc2dc \Ud30c\Uc774\Uc36c";
title = "\Ud30c\Uc774\Uc36c \Ud504\Ub85c\Uadf8\Ub798\Ubc0d";
user = 1;
};
pk = 11;
}
I want to show User model's username when make queryset, not user model's pk.
please Help me.

I think you need to change the Queryset to include that information.
detailContents = CommunityBoard.objects.filter(pk=pk).values_list('contents', 'title', 'user__username')
returnValues = serializers.serialize('json', detailContents)

You can make use of natural keys during serialization.
So you can try this:
returnValues = serializers.serialize('json', detailContents,
use_natual_keys=True)

Related

django serializer field not recognizing attribute clearly defined

when i try to run a view I get this error:
AttributeError: Got AttributeError when attempting to get a value for field `inreplytouser` on serializer `ContentFeedPostCommentSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'inreplytouser'.
Here is my model:
class ContentFeedPostComments(models.Model):
inreplytouser = models.ForeignKey(SiteUsers, null=True, related_name='replytouser', blank=True, on_delete=models.CASCADE)
inreplytotopcomment = models.BigIntegerField(null=True, blank=True)
timecommented = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(SiteUsers, on_delete=models.CASCADE)
contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE)
contentfeedpost = models.ForeignKey(ContentFeedPost, on_delete=models.CASCADE)
text = models.CharField(max_length=1000)
here is the serializer:
class ContentFeedPostCommentSerializer(ModelSerializer):
id = IntegerField()
inreplytouser = SiteusersSerializer()
user = SiteusersSerializer()
contentcreator = ContentCreatorSerializer()
class Meta:
model = ContentFeedPostComments
fields = ('id','inreplytouser', 'inreplytotopcomment', 'timecommented',
'user', 'contentcreator', 'contentfeedpost', 'text')
here is the view:
class ContentFeedPostsComments(APIView):
def get(self, request, *args, **kwargs):
postid = kwargs.get('postid')
contentfeedpost = get_object_or_404(ContentFeedPost, id=postid)
topcomments = ContentFeedPostComments.objects.filter(contentfeedpost= contentfeedpost, inreplytotopcomment= None).order_by('timecommented')
replycomments = ContentFeedPostComments.objects.filter( contentfeedpost = contentfeedpost, inreplytotopcomment__isnull = False).order_by('timecommented')
serializedtopcomments = ContentFeedPostCommentSerializer(topcomments)
serializedreplycomments = ContentFeedPostCommentSerializer(replycomments)
payload = {
'topcomments': serializedtopcomments.data,
'replycomments': serializedreplycomments.data
}
return Response(payload)
I was reading something about source being passsed into the inreplytouser field of the serializer field but that makes no sense. Your wisdom and knowledge on this situation is greatly appreciated.
Since querysets are a collection of objects, many=True..[DRF-doc] needs to be set in the serializer:
serializedtopcomments = ContentFeedPostCommentSerializer(topcomments, many=True)
serializedreplycomments = ContentFeedPostCommentSerializer(replycomments, many=True)

insert nested relationships in DB django

Need help , i am trying to push nested relations inside DB don't know where I am going wrong in this, is there something wrong with validated_data , which is a list of dict here , thanks in advance
class CatalogSerializer(serializers.ModelSerializer):
catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True)
class Meta:
model = Catalog
fields = ['created_by','client','catalog_products','created_datetime','is_active']
def create(self,validate_data):
client_id = validate_data.pop('id')
client = User.objects.get(id=client_id),
catalog_obj = Catalog.objects.create(
client = client,
created_by = self.context['user'],
is_active =True,
)
for pricelist_ins in validate_data:
CatalogProducts.objects.create(
catalog = catalog_obj,**pricelist_ins)
return catalog_obj
Basic Viewset
class CatalogViewset(viewsets.ModelViewSet):
queryset = Catalog.objects.all()
serializer_class = CatalogSerializer
permission_classes = []
authentication_classes = []
def create(self, request, *args, **kwargs):
if request.data:
try:
serialized_data = self.get_serializer(data = request.data)
if serialized_data.is_valid(raise_exception=True):
serialized_data.save()
return Response(serialized_data.data,status=200)
except Exception as e:
return Response({'error':str(e)},status=400)
return Response({'status':'invalid request'},status=400)
the error I am getting in Postman
{
"error": "{'catalog_products': [ErrorDetail(string='This field is required.', code='required')]}"
}
data i am posting
{
"id":"2",
"pricing_list":[
{
"from_quantity":"101",
"to_quantiy":"34",
"price":"1000"
},
{
"from_quantity":"10",
"to_quantiy":"501",
"price":"2000"
}
]
}
You have catelogue_products in the fields, it is by default required. But you are not posting any catelogue_products. You need to post data based on the fields of the serializer. validated data will not contain any other data, but valid data that was set in serializer.
To make it optional you may try to add required=False in the serialzier like this:
class CatalogSerializer(serializers.ModelSerializer):
catalog_products = CatalogProductsSerializer(source = 'catalogproducts_set',many=True, required=False)
class Meta:
model = Catalog
fields = ['created_by','client','catalog_products','created_datetime','is_active']

How to Create ,Get and update JSON data in Django model Text field?

I seen many answer related this problem but I confused how to implement this.
My requirement is:
(Create)First create data with key and value:
{"pradip" : 80} and store in user_rate_details model field.
(Update)Second time append new data in this field :
{"pradip" : 80,"exz" : 70} and save it.
How to achieve this in my views..
models.py:
class UserPhoto(models.Model):
user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto')
......
rated_by = models.ManyToManyField(Profile,blank=True,related_name='rate_by')
user_rate_details = models.TextField() ⬅⬅⬅⬅⬅ Here store JSON data
created_date = models.DateTimeField(auto_now_add=True)
views.py:
class PhotoRate(APIView):
permission_classes = [IsAuthenticated]
def get_userPhoto(self,pk):
try:
return UserPhoto.objects.get(id = pk)
except UserPhoto.DoesNotExist:
raise Http404
def post(self,request,formate = None):
pk = request.data.get('photo_id')
rate = request.data.get('rate')
photo = self.get_userPhoto(pk)
???????? How to create or update Json data here???
return Response(??JSON DATA??)
Any other best way you know please tell me..
Thank you..
i really do not understand your question but if you intend to store json data in your model field, then you could try...
in your model:
import json
#property
def user_rate_details(self):
return json.loads(self.user_rate_details)
in your view:
pk = request.data.get('photo_id')
rate = request.data.get('rate')
photo = self.get_userPhoto(pk)
details = photo.user_rate_detail
details['rate'] = int(rate)
photo.user_rate_details = json.dumps(details)
photo.save(update_fields=['user_rate_details'])
return Response()
Create Text field in model and dump or load JSON data..
models.py:
import json
class UserPhoto(models.Model):
user = models.ForeignKey(to = User,on_delete = models.CASCADE,related_name='userPhoto')
......
rated_by = models.ManyToManyField(Profile,blank=True,related_name='rate_by')
user_rate_details = models.TextField(default="{}")
created_date = models.DateTimeField(auto_now_add=True)
#property
def rate_details(self):
return json.loads(self.user_rate_details)
views.py:
class PhotoRate(APIView):
permission_classes = [IsAuthenticated]
def get_userPhoto(self,pk):
try:
return UserPhoto.objects.get(id = pk)
except UserPhoto.DoesNotExist:
raise Http404
def post(self,request,formate = None):
pk = request.data.get('photo_id')
rate = request.data.get('rate')
photo = self.get_userPhoto(pk)
user_dict = photo.rate_details
user_dict[self.request.user.username] = int(rate)
photo.user_rate_details = json.dumps(user_dict)
photo.save(update_fields=['user_rate_details'])
return Response({"Success" : "Rate submited!!"},status=status.HTTP_200_OK)
def patch(self,request,formate=None):
pk = request.data.get('photo_id')
photo = self.get_userPhoto(pk)
rate_detail = photo.rate_details
return Response({"Rated Users" : rate_detail},status=status.HTTP_200_OK)

Cannot assign "42": "Event.user_id" must be a "User" instance

I have checked all the solutions related to my question but no one worked, i have an event table in which i am assigning the id of user. Event Model is
class Event(models.Model):
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
event_auth_id=models.CharField(null=True, max_length=225)
event_title=models.CharField(max_length=225)
ticket_title=models.CharField(max_length=225)
category=models.CharField(max_length=50)
event_summary=models.TextField()
event_information=models.TextField()
restriction=models.CharField(max_length=50, default='No Restriction')
artist_image=models.CharField(null=True, max_length=50)
event_poster=models.CharField(null=True, max_length=50)
notification_email=models.CharField(null=True, max_length=50)
notification_frequency=models.CharField(null=True, max_length=15)
name_on_ticket=models.CharField(max_length=225)
event_tnc=models.TextField()
current_step=models.IntegerField(null=True)
event_status=models.BooleanField(default=True)
created=models.DateTimeField(auto_now=True)
modified=models.DateTimeField(auto_now_add=True)
I am assigning the logged in user id from view
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
But its giving me error
Cannot assign "42": "Event.user_id" must be a "User" instance.
The problem is in this code:
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
In the place of "user_id = request.user.id" You should use "user_id = request.user" or "user_id = request.user.username" because in the field
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
of Event model,you assigned user_id as a foreign key of User model,So user_id field is expecting a User instance,not request.user.id
Thanks.
The ForeignKey field is expecting an object of type User, not the user ID. Try changing the assignment user_id = request.user.id to user_id = request.user. It might also make sense to rename the field to "user" to avoid confusion in the future.

Django inline forms with multiple foreign keys

I'm trying to use Django's ModelForm and inline forms in my templates. However, I cannot find any documentation that maps neatly to a database model with multiple foreign keys back to the same table. These are my models:
# models.py
class Universities(models.Model):
name = models.CharField(max_length=100)
class Majors(models.Model):
name = models.CharField(max_length=80)
class Resumes(models.Model):
name = models.CharField(max_length=70)
undergrad = models.ForeignKey(Universities, related_name='undergrad_university')
undergrad_major = models.ForeignKey(Majors, related_name='undergrad_major')
grad = models.ForeignKey(Universities, related_name='grad_university')
grad_major = models.ForeignKey(Majors, related_name='grad_major')
How can I have Django generate a form for submitting Resumes where users can type in their university name and major? All four of which would be used to create new entries in their respective databases (2 in Universities, 2 in Majors) before saving the new resume similar to how the inline formset example works for a singular foreign key.
EDIT2 : For making a form. I guess I'd have done a personalized form with overriding of save() method, something like this (forms.py):
class YourForm(forms.Form):
fname = forms.CharField(label="name",max_length=70,validators=[#Choose your validators here])
fundergrad = forms.CharField(label="fundergrad",max_length=100,validators=[#Choose your validators here])
fundergrad_major = forms.CharField(label="fundergrad_major",max_length=80,validators=[#Choose your validators here])
fgrad = forms.CharField(label="fgrad",max_length=100,validators=[#Choose your validators here])
fgrad_major = forms.CharField(label="fgrad_major",max_length=80,validators=[#Choose your validators here])
def save(self, datas):
res = Resumes()
res.name = datas['fname']
undergrad = Universities()
undergrad_major = Majors()
grad = Universities()
grad_major = Majors()
undergrad.name = datas['fundergrad']
undegrad_major.name = datas['fundergrad_major']
grad.name = datas['fgrad']
grad_major.name = datas['fgrad_major']
undergrad.save()
undergrad_major.save()
grad.save()
grad_major.save()
res.undergrad = undergrad
res.undergrad_major = undergrad_major
res.grad = grad
res.grad_major = grad_major
res.save()
return res
In views.py :
def formView(request) :
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
datas={}
datas['fundergrad']=form.cleaned_data['fundergrad']
datas['fundergrad_major']=form.cleaned_data['fundergrad_major']
datas['fgrad']=form.cleaned_data['fgrad']
datas['fgrad_major']=form.cleaned_data['fgrad_major']
form.save(datas)
#Then do what you have to do in your view
EDIT1 : (doesn't answer the question, but it could help someone maybe so I let it here)
I would have tried with something like this in admin.py:
class UniversitiesInline1(admin.StackedInline):
model = Universities
fk_name = "undergrad"
class UniversitiesInline2(admin.StackedInline):
model = Universities
fk_name = "grad"
class MajorsInline1(admin.StackedInline):
model = Majors
fk_name = "undergrad_major"
class MajorsInline2(admin.StackedInline):
model = Majors
fk_name = "grad_major"
class ResumesAdmin(admin.ModelAdmin)
inlines = [
UniversitiesInline1,
UniversitiesInline2,
MajorsInline1,
MajorsInline2,
]
admin.site.register(Resumes, ResumesAdmin)
Explanations : https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-a-model-with-two-or-more-foreign-keys-to-the-same-parent-model