How to edit many to many relation different ways in Django admin - python

Models.py
class Movie(models.Model):
categories = ManyToManyField('Category', blank=True)
class Category(models.Model):
grouping = CharField(choices=CategoryGroupings)
where CategoryGroupings is one of 'genre', 'holiday', or 'custom'
Question
In the Movie Django admin, I would like to have three autocomplete_fields, one for each of the individual category types. I can't add 'categories' three times to the autocomplete_fields array. Without altering the model field definitions (ie without needing a migration), how would I manage this?

Related

Django Problem : I want to see reverse order in django admin many to many field

This is my model.py code
class Question(models.Model):
id = models.AutoField
question = models.CharField(max_length=100)
answer = models.CharField(max_length=100)
class TestSeries(models.Model):
id = models.AutoField
quiz_name = models.CharField(max_length=100)
all_question=models.ManyToManyField(MyQuestion)
When i open my admin panel on test series
previous added are shown in order : Oldest first
I want to see that in newest first manner.
There are two things OP needs to do
Store in the models when the object was created / updated.
Order based on the creation date. To do so, one can add to the model a Meta option named ordering or define a custom form to be used in the Django Admin. Example 1, Example 2.

Django model with Charfield Count and Zero values

I have a Django database model that has some attributes, one of them is a Charfield 'category' with Choices.
I now want to annotate a queryset of this model with the count of the rows of each category. The thing is, the way i know to do it, only categories present in the queryset are getting counted, but i want a queryset with all categories annotated with the count (0 if no rows with this category).
This is what im doing at the moment:
Model.objects.all().values('category').annotate(total=Count('category'))
Is there a way to display all categories, including such with count 0?
You can not count categories that do not exist, since, well... these do not exist. The choices are not even transferred to the database.
Using a CharField with choices is not the ideal modeling for this. Typically it is better to make a model Category and then another MyModel with ForeignKey [Django-doc] to link a MyModel object to a Category, so:
class Category(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class MyModel(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
then we can create categories like:
Category.objects.bulk_create(
Category(name='technology'),
Category(name='art'),
Category(name='science')
)
if we then link MyModel objects to these Categorys, we can annotate the Category with the number of MyModels with:
from django.db.models import Count
Category.objects.annotate(
num_mymodel=Count('mymodel')
)
Here the Categorys that arise from this queryset will have an extra attribute .num_mymodel with the number of linked MyModel objects. Since a LEFT OUTER JOIN is performed, for Categorys without any MyModels, it will use 0.

How to Design my data model in django with many OneToMany relations

I have an entity in my application which has some attribute like auth.User but it has also some extra attributes. So I created a OneToOne relationship with auth.User
class UserEntity(models.Model):
user = models.OneToOneField(User)
... other fields ...
I also have a Person model which is UserEntity so created it as this:
class Person (models.Model):
userEntity = models.OneToOneField(UserEntity)
... other fields ...
There are many different attributes like addresses,experiences,education and other details that I want to associate with my Person. A Person can have many addresses,experiences,education,speciality
I have a Speciality Model like this.
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
... other fields ...
The problem is how should I my data model be designed so that I can retrieve a person/user with all addresses,expereiences,specialities etc. I can associate each Person/user with Speciality since Speciality is an independent model and can exist without a user. Currently I have created another model for each e.g for Speciality I have created
class PersonSpeciality(models.Model):
person = models.ForeignKey(Person)
specialities = models.ForeignKey(Speciality)
Can I design it in a better way so I can have fast searching and retrievals and no mess.
Thank you
If a Person can have multiple Specialities, then you can implement a oneToMany relationship, just by adding a foreignKey:
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
person = models.ForeignKey(Person)
However, if you have several Persons with the same specialities (let's say 10 Persons are Painters), you would have 10 different Painters entries.
To avoid duplication, you can implement a ManyToMany relationship :
class Speciality(models.Model):
name = models.CharField()
code = models.CharField()
person = models.ManyToManyField(Person)
Django will create a third table in your DB to handle that (you don't need to write your PersonSpeciality class).

How do I make a class a sub-group of another class?

from django.db import models
class products(models.Model): #Table name, has to wrap models.Model to get the functionality of Django.
name = models.CharField(max_length=200, unique=True) #Like a VARCHAR field
description = models.TextField() #Like a TEXT field
price = models.IntegerField()
def __unicode__(self): #Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
return self.name
class categories(models.Model):
I'm a python newbie and I'm trying to create an e-commerce store. As you can see above, I've created the products class, but in the Categories class, I need to include all the products I create come under a certain category. I have no clue how to do this.
Sounds like you just want a ForeignKey from Product to Category.
Take a look at Many to Many
I think a Product can belong to Many categories so it should have a ManyToMany relationship to the Category model.

Django: add model fields to list_display and display related values per entry

I have the following model definitions, see below.
models.py:
class Userstatus(models.Model):
label = models.CharField(...)
description = models.CharField(...)
class Foo(models.Model):
title = models.CharField(...)
visibility = models.ManyToManyField(Userstatus)
admin.py:
class FooAdmin(ModelAdmin):
list_display = ('id', 'title', )
admin.site.register(Foo, FooAdmin)
In the admin list view of "Foo" via FooAdmin the list_display list should include the "label"s from Userstatus so a column for each label will appear. I could create and call a method that creates the list for list_display.
But then no properties or callables actually exist that would allow me to return let's say a boolean for each label column, based on the visibility-many-to-many field.
What are my options? Should I try to intercept a callable or attribute request to Foo and create a boolean result on the fly? (Hitting the DB too often or making the columns sortable is another problem, but first things first).
Django documentation says ...
ManyToManyField fields aren't supported, because that would entail
executing a separate SQL statement for each row in the table. If you
want to do this nonetheless, give your model a custom method, and add
that method's name to list_display. (See below for more on custom
methods in list_display.)
Are you sure you want Userstatus to be a database table and not just a list of a few statuses that could be accessed through a "choices" tuple?

Categories

Resources