I need your help, is really basic.
I have two models, Autor and Post with a many to one relationship. I'm having problems retrieving the data in the html page. What I want to do is list all the posts for a specific Autor within a FOR and besides that I need to show the first name and last name of the autor out of the FOR.
I really appreciate your help.
class Autor(models.Model):
first_name = models.CharField(max_length=30, null=False, verbose_name='First Name')
last_name = models.CharField(max_length=30, null=False, verbose_name='Last Name')
def __str__(self):
return self.first_name
class Meta:
db_table = 'autor'
verbose_name = 'Autor'
verbose_name_plural = 'Autors'
ordering = ['id']
class Post(models.Model):
autor = models.ForeignKey(Autor, on_delete=models.CASCADE)
post = models.CharField(max_length=200, null=False, verbose_name='Post')
def __str__(self):
return self.post
class Meta:
db_table = 'post'
verbose_name = 'Post'
verbose_name_plural = 'Posts'
ordering = ['id'] ```
Since you don't specify a related_name attribute in ForeignKey definition, Django automatically creates a related_name using the name of your model with the suffix _set, for example, if sample_author is an instance of Author, this query returns all posts of the sample_author:
author_posts = sample_author.post_set.all()
then you can use all posts that exist in the result of this query within a FOR loop.
for post in author_posts:
do something
outside of this loop, you can access to first_name and last_name of the sample_author instance by sample_author.first_name and sample_author.last_name
.
Related
I am new to Django rest framework, I want to get a list of the
student first names(only) when it is existed. can anyone help me?
In my models.py
class School(models.Model):
name = models.CharField(max_length=100, null=False, blank=False)
city = models.CharField(max_length=100, null=False, blank=False)
street = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return f"{self.city}->{self.street}->{self.name}"
class Student(models.Model):
school_id = models.ForeignKey(School, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100, null=False, blank=False)
last_name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return f"{self.first_name} {self.last_name}"
In my serializers.py:
class StudentSerializer(serializers.Serializer):
class Meta:
model = Student
fields = ['first_name']
class SchoolSerializer(serializers.Serializer):
is_existing_student = = serializers.BooleanField()
student = StudentSerializer(many=True, read_only=True)
class Meta:
model = School
fields = ['is_existing_student','student']
In my views.py:
class schoolViewSet(viewsets.ModelViewSet):
serializer_class = SchoolSerializer
queryset = School.objects.all()
In this picture you can see how it should look like
[1]: https://i.stack.imgur.com/bR8cN.png
you can try using values() method or values-list() method
so you can do something like
Student.objects.values_list('first_name')
or
Student.objects.values('first_name')
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#values-list
try adding a student view in your views.py then use values() method
class StudentViewSet(viewsets.ModelViewSet):
serializer_class = StudentSerializer
queryset = Student.objects.values('first_name')
From what you define on first_name model field, i.e null=False, blank=False. It means the field cannot be empty.
first_name = models.CharField(max_length=100, null=False, blank=False)
Which means all your models call will always have first_name required
Meanwhile, if you still want to be sure that your query returns items with first_name, do this
queryset = School.objects.exclude(student__first_name=None)
I am using Django 2.0
I have two models
class Chapter(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
name = models.CharField(max_length=250, blank=False)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
class META:
verbose_name_plural = 'chapters'
db_table = 'chapters'
def __str__(self):
return self.name
class ChapterQuestion(models.Model):
chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
word = models.CharField(max_length=250)
definition = models.CharField(max_length=250)
class META:
verbose_name_plural = 'chapter questions'
db_table = 'chapter_questions'
def __str__(self):
return self.word
Since Each ChapterQuestion belongs to only one Chapter, I think it could be Many-to-one relation.
My admin.py contain only
admin.site.register(Chapter)
admin.site.register(ChapterQuestion)
I want to be able to add/edit multiple questions while creating/editing chapter using Django Admin.
But Django Admin is showing only chapter fields
Also, I want created_by column to be field automatically by logged in user and remove from form.
You need to use inline forms
class ChapterQuestionInline(admin.StackedInline):
model = ChapterQuestion
#admin.register(Chapter)
class ChapterAdmin(admin.ModelAdmin):
list_display = ["course","name","created_by"]
inlines = [ChapterQuestionInline]
I'm beginner in python and Django rest And I stuck when I fetch data.
Here is my API :- http://127.0.0.1:8000/subjects/course/23/
I want a all subject data according to course which I select..When I hit this api if single data present working awesome but when inside course_id multiple subject present then gives me error such as :
Exception Type: MultipleObjectsReturned
Exception Value: get() returned more than one Subject -- it returned 2!
Here is my model.py
class Subject(models.Model):
course = models.CharField(max_length=255, blank=False, unique=False)
subject = models.CharField(max_length=255, blank=False, unique=False)
description = models.CharField(max_length=255, blank=False, unique=False)
amount = models.CharField(max_length=255, blank=False)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return "{}".format(self.title)
Here is my serializer.py
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = Subject
fields = ('id', 'course', 'subject', 'description', 'amount', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
lookup_field = 'course'
Here is my views.py
class ViewSubjectAccordingCourse(generics.RetrieveUpdateDestroyAPIView):
"""This class handles the GET and POSt requests of our rest api."""
queryset = Subject.objects.all()
serializer_class = SubjectSerializer
lookup_field = 'course'
Here is my urls.py
url(r'^subjects/course/(?P<course>[0-9]+)/$', ViewSubjectAccordingCourse.as_view(), name="details"),
so the problem is
course = models.CharField(max_length=255, blank=False, unique=False)
this value is identical for more then one subject, as you send in unique=False this seems to be by design, is the plan to have one or more subjects per course?
If its meant to be many subjects, you need to use the ListAPIView and some get_queryset modifications. If course is ment to only have a single Subject then change the field to unique=True
I have two models Company and Campaign. I need to create a relationship between them. I think my models are fine.
companies/model.py
class Company(models.Model):
class Meta:
verbose_name_plural = "companies"
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(blank=False, max_length=128, default='')
slug = models.SlugField(blank=True, unique=True)
archived = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
campaigns/models.py
class Campaign(models.Model):
class Meta:
verbose_name_plural = "campaigns"
company = models.ForeignKey('companies.Company', on_delete=models.CASCADE,)
title = models.CharField(blank=False, max_length=128, default='')
slug = models.UUIDField(default=uuid.uuid4, blank=True, editable=False)
def __str__(self):
return str(self.title)
campaigns/forms.py
class CampaignForm(forms.ModelForm):
class Meta:
model = Campaign
fields = ['title','description','archived']
campaigns/views.py
class CampaignCreateView(SubmitBtnMixin, CreateView):
model = Campaign
company = None
form_class = CampaignForm
submit_btn = "Add Campaign"
template_name = "form.html"
campaigns/urls.py
url(r'^campaign/create/$', CampaignCreateView.as_view(), name='campaign-create'),
My question is, when creating a new campaign, where and how do I pick up the Company pk to populate the Campaign model? What is the most secure and best practice for doing this?
I found a solution but would like input on best practices still.
I added this to my CampaignCreateView
def form_valid(self, form):
company = get_object_or_404(Company, id=self.kwargs.get('pk'), user_id=self.request.user.id)
form.instance.company_id = company.id
return super(CampaignCreateView, self).form_valid(form)
and I changed my url to:
url(r'^campaign/(?P<pk>\d+)/create/$', CampaignCreateView.as_view()...
Not sure that I like the pk in the URL since it can be jacked. This is why I am filtering on the userid at the company model to make sure that the data is coming from the owner.
I thought of doing this by registering the company in the session id but I am not convinced that sessions do not present their own problems.
I am a django newbie and have one more big struggle for longer time... :/
User can choose a 'main language' which is set as ForeignKey. User can choose 'further languages' as ManyToMany (Checkbox). Assuming, user selects english as 'main' language, so english has to be filterd out from the 'further languages'... have been searching so much and have no idea how to do it. Is this even possible without JavaScript?
Of course, I could set the 'queryset' in the second form but it would filter the objects after the submit... The similar problem is, when a selected country has to be connected to the proper zipcodes...
I am very thankful for any hints.
Best regards.
class Country(models.Model):
enter code here
country = models.CharField(max_length=40)
active = models.BooleanField(default=True)
class Meta:
verbose_name_plural = 'Länder'
def __str__(self):
return self.country
class ZipCode(models.Model):
zipcode = models.CharField(max_length=5)
city = models.CharField(max_length=255)
active = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'Postleitzahlen'
def __str__(self):
return '{0} {1}'.format(self.zipcode, self.city)
class MainLanguage(models.Model):
language = models.CharField(verbose_name='Hauptsprache', max_length=40)
active = models.BooleanField(default=True)
class Meta:
verbose_name_plural = 'Hauptsprachen'
ordering = ['language']
def __str__(self):
return self.language
class SecondLanguage(models.Model):
language = models.CharField(verbose_name='weitere Sprachen', max_length=40)
active = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'weitere Sprachen'
ordering = ['language']
def __str__(self):
return self.language
class CustomUserprofile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(verbose_name='Vorname', max_length=40,
null=True, blank=True)
country = models.ForeignKey(Country, verbose_name='Land',
null=True, blank=True)
zipcode = models.ForeignKey(ZipCode, blank=True, null=True)
main_language = models.ForeignKey(
MainLanguage, verbose_name='Hauptsprache',
null=True, blank=True)
second_language = models.ManyToManyField(
SecondLanguage, verbose_name='weitere Sprachen',
null=True, blank=True)
class UserProfileForm(forms.ModelForm):
second_language = forms.ModelMultipleChoiceField(
queryset=SecondLanguage.objects.all(),
required=False,
widget=forms.CheckboxSelectMultiple)
class Meta:
model = CustomUserprofile
exclude = ('user',)