This is my code
models.py(App: Article)
from django.contrib.auth.models import User
class Article(models.Model):
# code...
url_title = models.CharField(max_length=80, unique=True, db_index=True)
HATE_SPEECH = 'HS'
SPAM = 'SP'
FAKE_INFO = 'FI'
REPORT_REASON = (
(FAKE_INFO, 'Fake Information'),
(HATE_SPEECH, 'Hate Speech'),
(SPAM, 'Spam'))
class Report(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
article_id = models.ForeignKey(Article, on_delete=models.PROTECT)
user_id = models.ForeignKey(User, on_delete=models.PROTECT)
reason = models.CharField(max_length=2, choices=REPORT_REASON)
solved_status = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=now)
admin.py(App: Article)
class ArticleAdmin(admin.ModelAdmin):
pass
# code...
class ReportAdmin(admin.ModelAdmin):
list_display = ('id', 'article_id', 'user_id', 'reason', 'solved_status', 'date_created')
admin.site.register(Article, ArticleAdmin)
admin.site.register(Report, ReportAdmin)
My database records currently looks like this:
In django admin I want to display all these records in such a manner.
ordering = ['solved_status']
)So, the final Table should look something like this:
Now, we can see that
I tried using annotate using this link which I thought could solve my partial doubt, but it is constantly giving me errors and doubt yet not being solved. I am trying this for a long time, any help is appreciable. Thanks in advance :)
Some window function annotations should enable the described ordering:
from django.db.models import F, Count, Window, Q
class ReportAdmin(admin.ModelAdmin):
list_display = ('id', 'article_id', 'user_id', 'reason', 'solved_status', 'date_created',
'count_by_article', 'count_by_article_and_reason')
def get_queryset(self, request):
return super().get_queryset(request).annotate(
count_by_article=Window(
expression=Count('id', filter=Q(solved_status=False)),
partition_by=F('article_id')
),
count_by_article_and_reason=Window(
expression=Count('id', filter=Q(solved_status=False)),
partition_by=[F('article_id'), F('reason')],
),
earliest_report_by_article=Window(
expression=Min('date_created', filter=Q(solved_status=False)),
partition_by=[F('article_id')],
),
earliest_report_by_article_and_reason=Window(
expression=Min('date_created', filter=Q(solved_status=False)),
partition_by=[F('article_id'), F('reason')],
),
).order_by('solved_status', '-count_by_article', 'earliest_report_by_article', 'article_id',
'-count_by_article_and_reason', 'earliest_report_by_article_and_reason',
'reason', 'date_created')
def count_by_article(self, obj):
return obj.count_by_article
def count_by_article_and_reason(self, obj):
return obj.count_by_article_and_reason
admin.site.register(Report, ReportAdmin)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With