List is empty but shouldn't be - python

membership = GroupMembers.objects.filter(profile=profile.id, accepted__isnull=False).values_list('group', flat=True)
When I don't use values_list, I have one element in membership. But I just want to have a list with all the attributes "group" of the GroupMembers models. So I learned about values_list. However, now this will give me an empty list. What is wrong?
EDIT:
class Profile(models.Model):
id = models.AutoField(primary_key=True, db_column='profile_id')
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(blank=True, null=True, default=None, max_length=500)
group_set = models.ManyToManyField(Group, through='GroupMembers')
file_set = models.ManyToManyField(File, blank=True)
user_code = models.TextField(blank=True, null=True, default=None)
class GroupMembers(models.Model):
id = models.AutoField(primary_key=True, db_column='group_profile_id')
group = models.ForeignKey(Group, db_column='group_id')
profile = models.ForeignKey(Profile, db_column='profile_id')
rank = models.CharField(max_length=45, null=True, default=None, blank=True)
invited = models.DateTimeField(auto_now_add=True)
accepted = models.DateTimeField(null=True, default=None, blank=True)
rejected = models.DateTimeField(null=True, default=None, blank=True)
is_admin = models.BooleanField(default=False)

Related

Django Relational managers

I was trying to delete my Apllication model:
class Application(models.Model):
app_type = models.ForeignKey(ApplicationCategory, on_delete=models.CASCADE, related_name='applications')
fio = models.CharField(max_length=40)
phone_number = models.CharField(max_length=90)
organisation_name = models.CharField(max_length=100, null=True, blank=True)
aid_amount = models.PositiveIntegerField()
pay_type = models.CharField(max_length=1, choices=PAY_CHOICES, default=PAY_CHOICES[0][0])
status = models.ForeignKey(AppStatus, on_delete=models.CASCADE, related_name='applications', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
benefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE, related_name='applications', null=True)
def __str__(self):
return f"id={self.id} li {self.fio} ning mablag\'i!"
and this was my Benefactor model:
class Benefactor(models.Model):
fio = models.CharField(max_length=255)
phone_number = models.CharField(max_length=9)
image = models.ImageField(upload_to='media/')
sponsory_money = models.IntegerField()
organisation_name = models.CharField(max_length=55, null=True, blank=True)
def __str__(self):
return f"{self.fio}"
But I got the below message on superAdmin Panel:
TypeError at /admin/api/benefactor/
create_reverse_many_to_one_manager.\<locals\>.RelatedManager.__call__() missing 1 required keyword-only argument: 'manager'
I would expect delete smoothly!!
Your Benefactor model has several ForeignKey relationships that share the related_name. Give each a unique name and rerun your migrations.

Django filterset and Django rest framework not working as expected

I have created a Django filter set to filter data, some fields are filtered with relationships.
When I never filter with the endpoint, it just returns all data instead of filtered data, what could be wrong here?
This is my endpoint filterer :
http://127.0.0.1:5000/api/v1/qb/questions/?paper=26149c3b-c3e3-416e-94c4-b7609b94182d&section=59bdfd06-02d4-4541-9478-bf495dafbee1&topic=df8c2152-389a-442f-a1ce-b56d04d39aa1&country=KE
Below is my sample :
from django_filters import rest_framework as filters
class QuestionFilter(filters.FilterSet):
topic = django_filters.UUIDFilter(label='topic',
field_name='topic__uuid',
lookup_expr='icontains')
sub_topic = django_filters.UUIDFilter(label='sub_topic',
field_name='topic__sub_topic__uuid',
lookup_expr='icontains')
paper = django_filters.UUIDFilter(label='paper',
field_name='paper__uuid',
lookup_expr='icontains')
section = django_filters.UUIDFilter(label='section',
field_name='section__uuid',
lookup_expr='icontains')
subject = django_filters.UUIDFilter(label='subject',
field_name="paper__subject__id",
lookup_expr='icontains'
)
year = django_filters.UUIDFilter(label='year',
field_name='paper__year__year',
lookup_expr="icontains")
country = django_filters.CharFilter(label='country',
field_name="paper__exam_body__country",
lookup_expr='icontains')
class Meta:
model = Question
fields = ['topic', 'section', 'paper', 'sub_topic', 'subject', 'year',
'country']
Then my view is like this :
class QuestionView(generics.ListCreateAPIView):
"""Question view."""
queryset = Question.objects.all()
serializer_class = serializers.QuestionSerializer
authentication_classes = (JWTAuthentication,)
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = QuestionFilter
Then the models attached to the filter are as below :
class Question(SoftDeletionModel, TimeStampedModel, models.Model):
"""Questions for a particular paper model."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
mentor = models.ForeignKey(User, related_name='question_mentor', null=True,
on_delete=models.SET_NULL)
paper = models.ForeignKey(Paper, max_length=25, null=True,
blank=True, on_delete=models.CASCADE)
question = models.TextField(
_('Question'), null=False, blank=False)
section = models.ForeignKey(QuestionSection,
related_name='section_question',
null=True, on_delete=models.SET_NULL)
topic = models.ForeignKey(Course, related_name='topic_question',
null=True, on_delete=models.SET_NULL)
question_number = models.IntegerField(_('Question Number'), default=0,
blank=False, null=False)
image_question = models.ImageField(_('Image question'),
upload_to='image_question',
null=True, max_length=900)
answer_locked = models.BooleanField(_('Is Answer locked'), default=True)
status = models.CharField(max_length=50, choices=QUESTION_STATUSES,
default=ESSAY)
address_views = models.ManyToManyField(CustomIPAddress,
related_name='question_views',
default=None, blank=True)
bookmarks = models.ManyToManyField(User, related_name='qb_bookmarks',
default=None, blank=True)
def __str__(self):
return f'{self.question}'
Paper Model
class Paper(SoftDeletionModel, TimeStampedModel, models.Model):
"""Paper model."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
subject = models.ForeignKey(Subject, related_name='subject',
null=True, on_delete=models.SET_NULL)
mentor = models.ForeignKey(User, related_name='paper_mentor', null=True,
on_delete=models.SET_NULL)
year = models.DateField(_('Year'), blank=False, null=False)
grade_level = models.ForeignKey(ClassGrade, related_name='grade_paper',
null=True, on_delete=models.SET_NULL)
exam_body = models.ForeignKey(ExamBody, related_name='exam_body_paper',
null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField(_('No of questions'),
blank=False, null=False)
number_of_sections = models.IntegerField(_('No of sections'),
blank=False, null=False)
color_code = ColorField(format='hexa', default='#33AFFF', null=True)
class Meta:
ordering = ['created']
def __str__(self):
return f'{self.subject.name} ({self.year})'
QuestionSection Model :
class QuestionSection(SoftDeletionModel, TimeStampedModel, models.Model):
"""Question paper sections e.g Section A, B, C etc."""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
section = models.CharField(
_('Question Section'), max_length=100, null=False, blank=False)
def __str__(self):
return f'{self.section}'
class Course(SoftDeletionModel, TimeStampedModel, models.Model):
"""
Topic model responsible for all topics.
"""
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
title = models.CharField(
_('Title'), max_length=100, null=False, blank=False)
overview = models.CharField(
_('Overview'), max_length=100, null=True, blank=True)
description = models.CharField(
_('Description'), max_length=200, null=False, blank=False
)
country = CountryField()
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
topic_cover = models.ImageField(
_('Topic Cover'), upload_to='courses_images',
null=True, blank=True, max_length=900)
grade_level = models.ForeignKey(
ClassGrade, max_length=25, null=True,
blank=True, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
ranking = models.IntegerField(
_('Ranking of a Topic'), default=0, help_text=_('Ranking of a Topic')
)
def __str__(self):
return self.title
class Meta:
verbose_name_plural = "Topics"
ordering = ['ranking']

Django - Getting an object from an object

I'm trying to get the object "Book" from prommotion. Book is a ForeignKey in "prommotion", and I filtered all the prommotions that are active. I need to get the "Book" object from the Prommotion if its active and return it.
(And I know promotion is spelled wrong)
Views:
class Book_PrommotionViewSet(viewsets.ViewSet):
def list(self, request):
queryset = Prommotion.objects.filter(active=True)
serializer = PrommotionSerializer(queryset, many=True)
return Response(serializer.data, HTTP_200_OK)
Prommotion Model:
class Prommotion(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
precent = models.DecimalField(decimal_places=2, max_digits=255, null=True, blank=True)
active = models.BooleanField(default=False)
date_from = models.DateField()
date_to = models.DateField()
book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'Prommotion'
verbose_name_plural = 'Prommotions'
Book Model:
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=255)
published = models.DateField()
edition = models.CharField(max_length=255)
isbn_code = models.CharField(max_length=255)
pages = models.IntegerField(blank=True, null=True, default=0)
description = models.TextField(null=True, blank=True)
cover = models.CharField(max_length=30, choices=Cover.choices(), default=None, null=True, blank=True)
genre = models.CharField(max_length=30, choices=Genre.choices(), default=None, null=True, blank=True)
language = models.CharField(max_length=30, choices=Language.choices(), default=None, null=True, blank=True)
format = models.CharField(max_length=30, choices=Format.choices(), default=None, null=True, blank=True)
publisher = models.CharField(max_length=30, choices=Publisher.choices(), default=None, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Book'
verbose_name_plural = 'Books'
The first way to get all Books that are related to your active promotions is to extract the book ids from the queryset and pass it to a Book filter
active_promotions = Prommotion.objects.filter(active=True)
Book.objects.filter(id__in=active_promotions.values('book_id'))
Or simply filter books with active promotions by using the double underscore syntax to follow relationships
Book.objects.filter(prommotion__active=True).distinct()

Two dependent conditions in exclude DJANGO

I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.

How can I create a Django model for a form in which users can choose to add more fields?

Is this the correct way to write out all the fields in models.py and forms.py? I am sure there must be a cleaner way to do this rather than individually listing out all fields and differentiating them with a number at the end.
I have looked into Django FormSets but I am not sure how I would use that with Django WizardForms.
Thank you
models.py
class Profile(models.Model):
education_school = models.CharField(max_length=500, null=True, blank=True)
education_degree = models.CharField(max_length=500, null=True, blank=True)
education_field = models.CharField(max_length=100, null=True, blank=True)
education_start = models.CharField(max_length=100, null=True, blank=True)
education_end = models.CharField(max_length=100, null=True, blank=True)
education_grade = models.TextField(null=True, blank=True)
education_description = models.TextField(null=True, blank=True)
education_school2 = models.CharField(max_length=500, null=True, blank=True)
education_degree2 = models.CharField(max_length=500, null=True, blank=True)
education_field2 = models.CharField(max_length=100, null=True, blank=True)
education_start2 = models.CharField(max_length=100, null=True, blank=True)
education_end2 = models.CharField(max_length=100, null=True, blank=True)
education_grade2 = models.TextField(null=True, blank=True)
education_description2 = models.TextField(null=True, blank=True)
education_school3 = models.CharField(max_length=500, null=True, blank=True)
education_degree3 = models.CharField(max_length=500, null=True, blank=True)
education_field3 = models.CharField(max_length=100, null=True, blank=True)
education_start3 = models.CharField(max_length=100, null=True, blank=True)
education_end3 = models.CharField(max_length=100, null=True, blank=True)
education_grade3 = models.TextField(null=True, blank=True)
education_description3 = models.TextField(null=True, blank=True)
education_school4 = models.CharField(max_length=500, null=True, blank=True)
education_degree4 = models.CharField(max_length=500, null=True, blank=True)
education_field4 = models.CharField(max_length=100, null=True, blank=True)
education_start4 = models.CharField(max_length=100, null=True, blank=True)
education_end4 = models.CharField(max_length=100, null=True, blank=True)
education_grade4 = models.TextField(null=True, blank=True)
education_description4 = models.TextField(null=True, blank=True)
education_school5 = models.CharField(max_length=500, null=True, blank=True)
education_degree5 = models.CharField(max_length=500, null=True, blank=True)
education_field5 = models.CharField(max_length=100, null=True, blank=True)
education_start5 = models.CharField(max_length=100, null=True, blank=True)
education_end5 = models.CharField(max_length=100, null=True, blank=True)
education_grade5 = models.TextField(null=True, blank=True)
education_description5 = models.TextField(null=True, blank=True)
forms.py
class ProfileFour(forms.Form):
education_school = forms.CharField()
education_degree = forms.CharField()
education_field = forms.CharField()
education_start = forms.ChoiceField(choices=years)
education_end = forms.ChoiceField(choices=years)
education_grade = forms.CharField(widget=forms.Textarea)
education_description = forms.CharField(widget=forms.Textarea)
education_school2 = forms.CharField()
education_degree2 = forms.CharField()
education_field2 = forms.CharField()
education_start2 = forms.ChoiceField(choices=years)
education_end2 = forms.ChoiceField(choices=years)
education_grade2 = forms.CharField(widget=forms.Textarea)
education_description2 = forms.CharField(widget=forms.Textarea)
education_school3 = forms.CharField()
education_degree3 = forms.CharField()
education_field3 = forms.CharField()
education_start3 = forms.ChoiceField(choices=years)
education_end3 = forms.ChoiceField(choices=years)
education_grade3 = forms.CharField(widget=forms.Textarea)
education_description3 = forms.CharField(widget=forms.Textarea)
education_school4 = forms.CharField()
education_degree4 = forms.CharField()
education_field4 = forms.CharField()
education_start4 = forms.ChoiceField(choices=years)
education_end4 = forms.ChoiceField(choices=years)
education_grade4 = forms.CharField(widget=forms.Textarea)
education_description4 = forms.CharField(widget=forms.Textarea)
education_school5 = forms.CharField()
education_degree5 = forms.CharField()
education_field5 = forms.CharField()
education_start5 = forms.ChoiceField(choices=years)
education_end5 = forms.ChoiceField(choices=years)
education_grade5 = forms.CharField(widget=forms.Textarea)
education_description5 = forms.CharField(widget=forms.Textarea)
you have ModelForm in django
class ProfileFour(form.ModelForm)
class Meta:
model = Profile
fields = '__all__' # you wand all field
# or
fields = ['education_school', 'education_degree' ..] # name the field you want
doc django's really good, read it.
https://docs.djangoproject.com/fr/3.0/topics/forms/modelforms/
edit: for completed the answer of #Countour-Integral
class Profil(models.Model)
username = models.charField()
...
class Education(models.Model)
profil = models.ForeignKey(Profil)
school = models.CharField()
degree = models.IntegerField()
field = models.CharField()
start = models.DateField()
end = models.DateField()
grade = models.CharField()
description = models.textField()
You're looking at this the wrong way. Firstly, your model should be updated to reflect your use case. If you don't know the fields ahead of time, you can use a JSONField contained in an ArrayField e.g
education = ArrayField(models.JSONField(default=dict), size=10, default=list)
Now that we've got that out of the way, the better way to do what you want is to have Education as a model, and then the Profile model would have a foreign key to Education. ie
class Education(models.Model):
school = models.CharField(max_length=50)
degree = models.CharField(max_length=50)
...rest of fields
Then your Profile model would have:
education = models.ForeignKey(Education, related_name="profile")
To get a varying number of education forms, you should take advantage of modelformset. Create your EducationForm as a normal modelForm instance, then:
EducationFormSet = modelformset_factory(Education, form=EducationForm, max_num=10, extra=1)
Instead of writting the same code 5 times you could just use a ManyToMany field.
class Profile(models.Model):
education_school = models.ManyToManyField( blank=True)
education_degree = models.ManyToManyField( blank=True)
education_field = models.ManyToManyField( blank=True)
education_start = models.ManyToManyField( blank=True)
education_end = models.ManyToManyField( blank=True)
education_grade = models.ManyToManyField( blank=True)
education_description = models.ManyToManyField( blank=True)
and then you could define each field seperately
class education_school(models.Model):
education_school = models.CharField(max_length=500, null=True, blank=True)
and so on with the other fields

Categories