How to implement foreign key in open erp - foreign-keys

I am new to open erp , I have two table master and details , i want to use id of master as foreign key in detail table. How can i achieve this?
Any one please help!!
My code is
from osv import osv,fields
class wlan_master(osv.osv):
_name = 'wlan_master'
_columns = {
'AP_name' :fields.char(),
'description' :fields.char(),
'ip_address' :fields.char(),
}
class wlan_details(osv.osv):
_name = 'wlan_details'
_columns = {
'wireless_workmode' :fields.char(),
'enable_wireless' :fields.char(),
'ssid' :fields.char(),
'channel' :fields.char(),
'wireless_mode' :fields.char(),
'channel_bandwidth' :fields.char(),
'rate' :fields.char(),
'broadcast_ssid' :fields.char(),
'client_isolation' :fields.char(),
'wmm_announcement' :fields.char(),
'fragement_threshold' :fields.char(),
'rts' :fields.char(),
'dtim_gap' :fields.char(),
'beacon_gap' :fields.char(),
'preamble_type' :fields.char(),
'encryption_mode' :fields.char(),
'filter_mode' :fields.char(),
}

Use one2many and many2one to link between tables.I have added detail_ids and master_id in your tables. please check it.
from osv import osv,fields
class wlan_master(osv.osv):
_name = 'wlan_master'
_columns = {
'AP_name' :fields.char(),
'description' :fields.char(),
'ip_address' :fields.char(),
'detail_ids': fields.one2many('wlan_details','master_id','Details')
}
class wlan_details(osv.osv):
_name = 'wlan_details'
_columns = {
'master_id': fields.many2one('wlan_master','Master'),
'wireless_workmode' :fields.char(),
'enable_wireless' :fields.char(),
'ssid' :fields.char(),
'channel' :fields.char(),
'wireless_mode' :fields.char(),
'channel_bandwidth' :fields.char(),
'rate' :fields.char(),
'broadcast_ssid' :fields.char(),
'client_isolation' :fields.char(),
'wmm_announcement' :fields.char(),
'fragement_threshold' :fields.char(),
'rts' :fields.char(),
'dtim_gap' :fields.char(),
'beacon_gap' :fields.char(),
'preamble_type' :fields.char(),
'encryption_mode' :fields.char(),
'filter_mode' :fields.char(),
}

Related

How to set lookup_field of GenericViewSet with JSONfield key?

How do I set the lookup_field with a key in JSONField model?
The model:
exchange = models.ForeignKey(StockExchange, on_delete=models.CASCADE, related_name='tickers')
fundamentals = models.JSONField(null=True, blank=True)
The viewset:
class StockCardsV2ViewSet(BaseGetViewSet):
search_fields = ('^fundamentals__General__Name', '^fundamentals__General__Code')
filter_backends = (filters.SearchFilter,)
queryset = Ticker.objects.all()
serializer_class = StockCardsV2Serializer
lookup_value_regex = '[0-9a-zA-Z_.]+'
lookup_field = 'fundamentals__General__Code'
The Serializer:
class Meta:
model = Ticker
fields = ('id', 'url', 'name', 'ticker', 'logo_url', 'currency_symbol', 'sector', 'industry', 'esg_rating',
'weekly_prices', 'monthly_prices', 'yearly_prices', 'two_yearly_prices', 'ad', 'in_watchlist')
lookup_field = 'fundamentals__General__Code'
extra_kwargs = {
'url': {'lookup_field': 'fundamentals__General__Code'},
}
There are no problems with search_fields but I get this error for the lookup_field.
'Ticker' object has no attribute 'fundamentals__General__Code'
Example fundamentals:
"fundamentals": {
"General": {
"CIK": null,
"LEI": null,
"Code": "SATX-WTA",
"ISIN": null,
"Name": "Satixfy Communications Ltd.",
}
},

TypeError: Object of type '_Serializer' is not JSON serializable

I am newer in Django rest api. My code is bellow:
class PatientViewSet(viewsets.ModelViewSet):
queryset = Patient.objects.all()
serializer_class = PatientSerializer
filter_backends = (DjangoFilterBackend, filters.OrderingFilter)
filterset_fields = ['id', 'email', 'mobile', 'status', 'type', 'gender']
ordering_fields = ['id', 'name']
def get_queryset(self):
queryset = Patient.objects.all()
status = self.request.query_params.get('status')
name = self.request.query_params.get('name')
if not status:
queryset = queryset.exclude(status="DELETE")
if name:
queryset = queryset.filter(name__icontains=name)
return queryset
def retrieve(self, request, pk=None):
queryset = Patient.objects.all()
patient = get_object_or_404(queryset, pk=pk)
serializer = PatientSerializer(patient)
summary = dict()
summary['payment'] = list(PatientPayment.objects.filter(patient_id=pk).aggregate(Sum('amount')).values())[0]
summary['appointment'] = DoctorAppointment.objects.filter(patient_id=pk).count()
d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last()
appoint_data = DoctorAppointmentSerializer(d_appoint)
summary['last_appointment'] = appoint_data
content = {"code": 20000, "data": serializer.data, "summary": summary}
return Response(content)
Here url is:
http://127.0.0.1:8000/api/patients/2/
When I run in postman it getting the error bellow:
TypeError at /api/patients/2/
Object of type 'DoctorAppointmentSerializer' is not JSON serializable
Here problem with the code snippet:
d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last()
appoint_data = DoctorAppointmentSerializer(d_appoint)
My question is how can I getting my result?
DoctorAppointmentSerializer Class:
class DoctorAppointmentSerializer(serializers.HyperlinkedModelSerializer):
patient = PatientSerializer(read_only=True)
patient_id = serializers.IntegerField()
doctor = DoctorSerializer(read_only=True)
doctor_id = serializers.IntegerField()
doc_image = Base64ImageField(
allow_null=True, max_length=None, use_url=True, required=False
)
doc_file = Base64ImageField(
allow_null=True, max_length=None, use_url=True, required=False
)
class Meta:
model = DoctorAppointment
fields = ['id', 'name', 'mobile', 'problem', 'age', 'gender', 'description', 'doctor', 'doctor_id', 'patient',
'patient_id', 'advice', 'doc_image', 'doc_file', 'created_at']
You have to call the .data property of DoctorAppointmentSerializer class
appoint_data = DoctorAppointmentSerializer(d_appoint).data
^^^^^^

How would i increment the name of the field, when field with the same name is created?

I have dropdown component on my front-end. What i am trying to do is.
Every time onChange event happens i want to add selected option value as role in my backend. That works just fine for first time the option value gets selected.
What i want to do is to increment the name of the Role, if it gets selected once again. If i select Developer twice, i want the second time data to be posted as Developer 1 etc...
How could i accomplish this?
I have been googling this for an hours, and i have not already figured it out. I have tried creating validators for my serializers, checking if object exists, then if it does incrementing it for 1, and other ways.
Model
class Role(models.Model):
address1 = models.TextField(name="address1", max_length=150, null=True)
address2 = models.TextField(name="address2", max_length=150, null=True)
vat = models.CharField(max_length=100, null=True)
categoryname = models.CharField(max_length = 100)
date_created = models.DateField(null=True)
is_active = models.BooleanField(null=True)
is_passive = models.BooleanField(null=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='roles', on_delete=models.CASCADE)
def get_owner_full_name(self):
return self.owner.get_full_name()
Serializers
from rest_framework import serializers
from .models import Role
from core.serializers import DynamicFieldsModelSerializer, BasicSerializer
from user.serializers import CustomUserSimpleSerializer
class RoleSerializerBasic(DynamicFieldsModelSerializer ,BasicSerializer,):
owner = serializers.ReadOnlyField(source='owner.username') #
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = ('address1', 'address2','vat','categoryname','date_created', 'owner')
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerDepth(DynamicFieldsModelSerializer ,BasicSerializer):
owner = serializers.ReadOnlyField(source='owner.username') #
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = '__all__'
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerInvestor(DynamicFieldsModelSerializer ,BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerAuditor(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
class RoleSerializerDeveloper(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
class RoleSerializerEducationalInstitution(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
import json
from django.views.generic import ListView
from rest_framework import generics, permissions, status
#from django_weasyprint import WeasyTemplateResponseMixin
#Redis
from django.conf import settings
#Own
from .models import Role
from .serializers import RoleSerializerBasic, RoleSerializerDepth, RoleSerializerDeveloper, RoleSerializerAuditor, RoleSerializerInvestor, RoleSerializerEducationalInstitution
from core.permissions import HasGroupPermission, HasObjectPermission
from core.mail import send_mail
from core.views import PBListViewMixin, PBDetailsViewMixin
# Views
class RoleList(PBListViewMixin, generics.ListCreateAPIView):
#permission_classes = (permissions.IsAuthenticated, HasGroupPermission, HasObjectPermission,)
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':100,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'):
return RoleSerializerDepth
return RoleSerializerBasic
def perform_create(self, serializer):
"""Save the post data when creating a new bucketlist."""
serializer.save(owner=self.request.user) # Add
class RoleDetails(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':500,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'):
return RoleSerializerDepth
return RoleSerializerBasic
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class RoleInvestor(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':100,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerInvestor
return RoleSerializerBasic
class RoleAuditor(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerAuditor
return RoleSerializerBasic
class RoleDeveloper(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerDeveloper
return RoleSerializerBasic
class RoleEducator(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerEducationalInstitution
return RoleSerializerBasic
My react code
onChange = (e,i) => {
console.log("values", e.target.value+1)
this.props.AddRole(e.target.value);
}
render(){
const roles = [
{ label: "Investor", value:"Investor"},
{ label: "Auditor", value:"Auditor" },
{ label: "Developer", value:"Developer"},
{ label: "Educational Institution", value:"Educational Institution"}
]
return (
<>
<div className="SelectOptionKlasa1">
<Select
name="roleSelect"
options={ roles}
label="Create new role"
onChange={this.onChange}
/>
</div>
</>
)
}
}
export const AddRole = (categoryname, owner) => async dispatch =>{
dispatch({ type: types.ADD_ROLE});
const address = `/roles/`;
const bodyFormData = new FormData();
bodyFormData.set("categoryname", categoryname);
console.log("username ")
apiCon.post( address, bodyFormData)
.then(res => {
dispatch(RoleAddedSuccessfuly(res.data));
console.log("Added role", res.data);
})
.catch(err => {
dispatch(RoleFailToAdd("Role could not be added. "+err));
})
}
I expect every time when i post role from my frontend, if there is already role created with that name new role to be created with the same name, but plus 1. Like Developer 1, Auditor 1. I am getting categoryname: ["role with this categoryname already exists."] when i send post request.

deal with one user model for multiple type of user in django rest framework

I'm trying to build a multiple type user api with django rest framework in my project i have two types of users:
-customer who is an individual user
-corporates who are companies
What i'm trying to achieve is to have two separates users on the admin apnel whith its own viewset at the endpoint but for django corporates and individual user are users so when i display my individual user endpoint in json django render information for customer&corporates but the only one i want in the json is customer information not a both it's same issue for corporates endpoint
here is my model:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
class User(AbstractUser):
username = models.CharField(blank=True, null=True, max_length=10)
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return "{}".format(self.email)
class PersonProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, related_name='profile')
nom = models.CharField(blank=True, null=True, max_length=50)
photo = models.ImageField(upload_to='uploads', blank=True)
dob = models.DateTimeField(auto_now_add=True)
address = models.CharField(blank=True, null=True, max_length=255)
contact_1 = models.CharField(blank=True, null=True, max_length=50)
contact_2 = models.CharField(blank=True, null=True, max_length=50)
country = models.CharField(blank=True, null=True, max_length=50)
city = models.CharField(blank=True, null=True, max_length=50)
class CorporateUserProfile(PersonProfile):
# profile = models.ForeignKey(PersonProfile)
representant_legal = models.CharField(blank=True, null=True,
max_length=50)
statut = models.CharField(blank=True, null=True, max_length=50)
class IndividualUserProfile(PersonProfile):
prenom = models.CharField(blank=True, null=True, max_length=50)
#class Meta:
# db_table = 'individual_user'
here is my serializers.py:
from rest_framework import serializers
from api.models import User, PersonProfile, CorporateUserProfile,
IndividualUserProfile
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
# model = PersonProfile
model = CorporateUserProfile
fields = ('nom', 'photo', 'dob', 'address', 'contact_1',
'contact_2', 'country', 'city',
'representant_legal', 'statut')
class UserSerializer(serializers.HyperlinkedModelSerializer):
profile = UserProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'password', 'profile')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
profile_data = validated_data.pop('profile')
password = validated_data.pop('password')
user = User(**validated_data)
user.set_password(password)
user.save()
CorporateUserProfile.objects.create(user=user, **profile_data)
return user
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
profile = instance.profile
instance.email = validated_data.get('email', instance.email)
instance.save()
profile.nom = profile_data.get('nom', profile.nom)
profile.photo = profile_data.get('photo', profile.photo)
profile.dob = profile_data.get('dob', profile.dob)
profile.address = profile_data.get('address', profile.address)
profile.contact_1 = profile_data.get('contact_1', profile.contact_1)
profile.contact_2 = profile_data.get('contact_2', profile.contact_2)
profile.country = profile_data.get('country', profile.country)
profile.city = profile_data.get('city', profile.city)
profile.representant_legal = profile_data.get('representant_legal', profile.representant_legal)
profile.statut = profile_data.get('statut', profile.statut)
profile.save()
return instance
class IndividualUserProfileSerializer(serializers.ModelSerializer):
class Meta:
# model = PersonProfile
model = IndividualUserProfile
fields = ('nom', 'prenom', 'photo', 'dob', 'address', 'contact_1', 'contact_2', 'country', 'city')
class IndividualSerializer(serializers.HyperlinkedModelSerializer):
profile = IndividualUserProfileSerializer(required=True)
class Meta:
model = User
fields = ('url', 'email', 'password', 'profile')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
profile_data = validated_data.pop('profile')
password = validated_data.pop('password')
user = User(**validated_data)
user.set_password(password)
user.save()
IndividualUserProfile.objects.create(user=user, **profile_data)
return user
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
profile = instance.profile
instance.email = validated_data.get('email', instance.email)
instance.save()
profile.nom = profile_data.get('nom', profile.nom)
profile.prenom = profile_data.get('nom', profile.prenom)
profile.photo = profile_data.get('photo', profile.photo)
profile.dob = profile_data.get('dob', profile.dob)
profile.address = profile_data.get('address', profile.address)
profile.contact_1 = profile_data.get('contact_1', profile.contact_1)
profile.contact_2 = profile_data.get('contact_2', profile.contact_2)
profile.country = profile_data.get('country', profile.country)
profile.city = profile_data.get('city', profile.city)
profile.save()
return instance
here is my views.py:
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from api.models import User
from api.serializers import UserSerializer, IndividualSerializer
# Also add these imports
from api.permissions import IsLoggedInUserOrAdmin, IsAdminUser
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Add this code block
def get_permissions(self):
permission_classes = []
if self.action == 'create':
permission_classes = [AllowAny]
elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update':
permission_classes = [IsLoggedInUserOrAdmin]
elif self.action == 'list' or self.action == 'destroy':
permission_classes = [IsAdminUser]
return [permission() for permission in permission_classes]
class IndividualViewSet(viewsets.ModelViewSet):
# queryset = User.objects.all()
queryset = User.objects.all()
serializer_class = IndividualSerializer
# Add this code block
def get_permissions(self):
permission_classes = []
if self.action == 'create':
permission_classes = [AllowAny]
elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update':
permission_classes = [IsLoggedInUserOrAdmin]
elif self.action == 'list' or self.action == 'destroy':
permission_classes = [IsAdminUser]
return [permission() for permission in permission_classes]
this what I have at the endpoint of individual user is a list of individual users and companies in the same json what went wrong?:
# Create your tests here.
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"url": "http://127.0.0.1:8000/api/users/1/",
"email": "vend#gmail.com",
"profile": null
},
{
"url": "http://127.0.0.1:8000/api/users/2/",
"email": "vendeur#gmail.com",
"profile": {
"nom": "noname",
"prenom": null,
"photo": null,
"dob": null,
"address": "BP 137 Yaounde rue1037",
"contact_1": "+237 668982566",
"contact_2": "+237 668982569",
"country": "Cameroun",
"city": "Yaounde"
}
},
{
"url": "http://127.0.0.1:8000/api/users/3/",
"email": "georges#gmail.com",
"profile": {
"nom": "noname",
"prenom": null,
"photo": null,
"dob": null,
"address": "BP 137 Douala rue 1137",
"contact_1": "+237 668982567",
"contact_2": "+237 668982570",
"country": "Cameroun",
"city": "Douala"
}
},
{
"url": "http://127.0.0.1:8000/api/users/4/",
"email": "jeiffey#gmail.com",
"profile": {
"nom": "noname",
"prenom": null,
"photo": null,
"dob": null,
"address": "BP 137 Bafoussam rue 1134",
"contact_1": "+237 668982568",
"contact_2": "+237 668982571",
"country": "Cameroun",
"city": "Bafoussam"
}
},
{
"url": "http://127.0.0.1:8000/api/users/5/",
"email": "degrasguemto#gmail.com",
"profile": {
"nom": "noname",
"prenom": null,
"photo": "http://127.0.0.1:8000/api/users/uploads/963840d34c51efe6fbe57749fb434646.jpg",
"dob": "2019-09-22T13:46:23.682584Z",
"address": "BP 137 Yaounde rue 5024",
"contact_1": "+237 691679613",
"contact_2": "+237 678590793",
"country": "Cameroun",
"city": "Yaounde"
}
},
{
"url": "http://127.0.0.1:8000/api/users/6/",
"email": "gdegras#gmail.com",
"profile": {
"nom": "degras",
"prenom": null,
"photo": "http://127.0.0.1:8000/api/users/uploads/Lamp-3D-Wallpaper-photos-images_VcIDh6z.jpg",
"dob": "2019-09-22T22:23:08.271455Z",
"address": "BP 3306 Yaounde rue 1137",
"contact_1": "+237 691679613",
"contact_2": "+237 678590793",
"country": "Cameroun",
"city": "Yaounde"
}
},
{
"url": "http://127.0.0.1:8000/api/users/7/",
"email": "IUTFV#gmail.com",
"profile": {
"nom": "IUT FV",
"prenom": null,
"photo": null,
"dob": "2019-09-22T22:25:22.702443Z",
"address": "BP 137 Bafoussam rue 1134",
"contact_1": "+237 668982566",
"contact_2": "+237 668982569",
"country": "Cameroun",
"city": "Yaounde"
}
}
]

return user id django

I have a model field
account_handler = models.ForeignKey(User, blank=True, null=True, related_name='handling_leads', on_delete=models.SET_NULL)
Currently I'm doing something like this
def get_queryset(self):
user_id = User.objects.all()
queryset = User.objects.filter(handling_leads__account_handler=user_id).distinct()
return queryset
and I've got some results for testing purposes. Now the question is, how can I properly use this field and return a user_id? I have tried something like this
User.objects.filter(handling_leads__account_handler=self.request.user.id).distinct()
with out User.objects.all() but that was just returning an empty queryset. I'm trying to filter this so I can populate a table with user__first_name and user__last_name, I need user_id so I can redirect them to their individual page.
controler for the datatable:
app = angular.module 'statistics'
app.controller 'SalesCommissionsListCtrl', ['$scope', '$compile',
($scope, $compile) ->
$scope.init = ()->
fetchCommissionsList()
fetchCommissionsList = ()->
$('#commissionsSalesList').DataTable({
createdRow: (row, data, index) ->
$compile(row)($scope)
sDom: 'lftip',
processing: true,
serverSide:true,
searchDelay: 1000,
orderMulti: false,
pageLength: 10,
ajax: {
url: '/api/statistics/commissions/list/',
data: (data)->
data.limit = data.length;
data.offset = data.start;
data.search = data.search['value'];
if (data.order[0]['dir'] == 'asc')
data.ordering = data.columns[data.order[0]['column']].name;
else
data.ordering = '-' + data.columns[data.order[0]['column']].name;
return 0
dataFilter: (data) ->
json = jQuery.parseJSON(data);
json.recordsTotal = json.count;
json.recordsFiltered = json.count;
json.data = json.results;
return JSON.stringify(json);
}
columns: [
{
data: "username",
name: "username__first_name, username__last_name",
render: (data, type, row, meta)->
return '' + data + '';
}
]
})
]
my ModelViewSet:
from django.contrib.auth.models import User
from rest_framework import viewsets, filters, permissions
from app.restapi.pagination import StandardResultsOffsetPagination
from statistics.restapi.serializers import SalesCommissionsSerializer
from statistics.restapi.permissions import SalesCommissionsListPermissions
class SalesCommissionsViewSet(viewsets.ModelViewSet):
def get_queryset(self):
user_id = User.objects.all()
queryset = User.objects.filter(handling_leads__account_handler=user_id).distinct()
return queryset
serializer_class = SalesCommissionsSerializer
filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filter_fields = (
'id', 'username', 'first_name', 'last_name'
)
ordering_fields = (
'id', 'username', 'first_name', 'last_name',
)
search_fields = (
'id', 'username', 'first_name', 'last_name',
)
pagination_class = StandardResultsOffsetPagination
permission_classes = [permissions.IsAuthenticated, SalesCommissionsListPermissions]
serializer:
from django.contrib.auth.models import User
from rest_framework import serializers
class SalesCommissionsSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name')
If you want to filter for users who are 'handling leads', you can do the following:
handling_leads = User.objects.filter(handling_leads__isnull=False)
Here's a link to the documentation: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#std:fieldlookup-isnull