Username from django auth_user as foreign key in another table - python

I have this model:
models.py
class InsertIP(models.Model):
sourceIP=models.CharField(max_length=18)
destinationIP=models.CharField(max_length=18)
port=models.CharField(max_length=10)
comment=models.CharField(max_length=200, null=True, blank=True)
class Meta:
db_table="fw_rules"
And I need to add column User which contains the name of user who creates the record. I need to create foreign key from username from django auth_user
Can you please help me?
Thank you.

You can do it like this:
class InsertIP(models.Model):
sourceIP = models.CharField(max_length=18)
destinationIP = models.CharField(max_length=18)
port = models.CharField(max_length=10)
comment = models.CharField(max_length=200, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
db_table="fw_rules"
Then in your view you will access it like this:
ip = InsertIp.objects.get(pk=pk) # query the InsertIp object
user = ip.user # get the user using a . operator

Related

Filtering data from 3 different tables in django with 1 intermediate table

I have four models in my django application with following structure:
class User(models.Model):
first_name = models.CharField()
last_name = models.CharField()
class Customer(models.Model):
kyc_record = models.ForeignKey(CustomerKYCRecord, on_delete=models.CASCADE,null=True,default=None)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class SomeItem(models.Model):
price = models.DecimalField()
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class SomeOtherItem(models.Model):
transaction_status = models.CharField(max_length=200, default='INITIATED')
some_item = models.ForeignKey(SomeItem, on_delete=models.CASCADE, unique=True)
I have to create an API and I have been given a list of SomeItem. I have to write a django queryset line to extract first_name and last_name from User model, all details of SomeItem model and all details of SomeOtherItem model(if present).
I also have to create a serializer to parse the data as a Python dict.
Will be great if one can help me in this.

Better way to fetch related object, in Self Refrencing ManyToMany Relationship?

I am working on a small application containing models CustomUser and PollQuestion. CustomUser having ManyToMany relation between itself and a CustomUser can have multiple PollsQuestion as well so there is Foreign Key relation between them.
An authenticated user is only able to see polls raised by users he is following, to full-fill this requirement i have written following view**:-**
Actually this is not view this is an utility method returning the polls to original view.
def all_polls_utils(request):
following = request.user.get_all_followings().values_list("id")
user_id = [id[0] for id in following]
all_polls = PollQuestion.objects.none()
for u_id in user_id:
user = CustomUser.objects.get(id=u_id)
polls = user.poll_questions.all()
all_polls = all_polls | polls
return all_polls
Main Question:- Is there in better way to do the same?
Any suggestion will be highly appretiated
I am posting the models bellow:-
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
email = models.EmailField(max_length=250, null=False)
name = models.CharField(max_length=50, null=False)
username = models.CharField(max_length=50, null=False, unique=True)
password = models.CharField(max_length=15, null=False)
user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to')
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['name', 'email']
def get_all_polls(self):
pass
def create_relationship(self, person):
status, obj = Relationship.objects.get_or_create(
to_person=person,
from_person=self,
)
return status
def remove_relationship(self, person):
Relationship.objects.filter(
from_person=self,
to_person=person
).delete()
return 'dummy_value'
def get_all_followings(self):
return self.user.all()
class Relationship(models.Model):
from_person = models.ForeignKey(CustomUser, related_name='from_people', on_delete=models.CASCADE)
to_person = models.ForeignKey(CustomUser, related_name='to_person', on_delete=models.CASCADE)
And PollQuestion:-
class PollQuestion(models.Model):
user = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE, related_name="poll_questions")
# Other fields
Note:- You can also suggest me a better title for this post?
Thanks in advance,
Hope to here from you soon.
Simply
def all_polls_utils(request):
all_polls_by_followed = PollQuestion.objects.filter(
user__in=request.user.get_all_followings()
)
As an aside, you should probably rename the user many-to-many in CustomUser to e.g. followed_users (with a related name followers).

Django - limit choices to foreign key

I have the following model in Django
class Transfer(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT, limit_choices_to={'is_accepted':True})
amount = models.IntegerField(default=0)
transfer_date = models.DateTimeField(default=timezone.now)
company = models.ForeignKey(Company, on_delete=models.PROTECT)
I would like to filter the users based on is_accepted field. The problem is, that this field is declared in a model called Employee, which is in onetoone relationship with user.
Is there any possibility to reach Employee fields and filter them in this manner?
You can normally define a filter like:
class Transfer(models.Model):
user = models.ForeignKey(
User,
on_delete=models.PROTECT,
limit_choices_to={'employee__is_accepted': True}
)
amount = models.IntegerField(default=0)
transfer_date = models.DateTimeField(default=timezone.now)
company = models.ForeignKey(Company, on_delete=models.PROTECT)

How to pass object assignment to a foreign key relationship in REST Framework?

I have two models:
class Group(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
class User(models.Model):
username = models.CharField(max_length=50, null=False, blank=False)
password = models.CharField(max_length=50, null=False, blank=False)
group = models.ForeignKey(Group, null=False, on_delete=models.CASCADE)
And I have serializers for both of them:
class GroupSerializer(serializers.Serializer):
name = serializers.CharField()
class UserSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
group = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all())
Then in the registration view, I'm trying to automatically create a group when user is registering their account:
#api_view(['POST'])
def registration(request):
# Creates a new group
g_serializer = GroupSerializer(data=request.data, partial=True)
g_serializer.is_valid(raise_exception=True)
group = g_serializer.save()
# Creates a new user
u_serializer = UserSerializer(data=request.data, partial=True)
u_serializer.is_valid(raise_exception=True)
user = u_serializer.save()
As you can imagine the error I'm getting is that group field for User class violates not null restriction.
I tried to fix it by doing u_serializer['group'] = group.id or u_serializer['group'] = group but it throws the following error:
TypeError: 'UserSerializer' object does not support item assignment
How can I handle this? The new Group object is being properly created and inserted into the db and I need to assign that object to user.group.
According to this https://stackoverflow.com/a/44718400/3734484 in your case would be:
...
# Creates a new user
u_serializer = UserSerializer(data=data, partial=True)
u_serializer.is_valid(raise_exception=True)
user = u_serializer.save(group=group)
...

Foreign key which related to other foreign key choice

I'm trying to make the following models in django:
class Client(models.Model):
client = models.CharField(max_length=200)
loyal = models.BooleanField(default=False)
class Contact(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
client_id = models.ForeignKey(Client, on_delete=models.SET_NULL,null=True)
class Activity(models.Model):
title = models.CharField(max_length=30)
text = models.CharField(max_length=1000)
client_id = models.ForeignKey(Client, on_delete=models.PROTECT)
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
What i want to achieve - when i creating an activity and choose client in it - i want that in contact field i have to choose only from the contacts which related to choosen client, because when i do:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT)
Django allow me to choose from all the contacts. I want to limit somehow the list of contacts from i need to choose, i try this way:
contact_id = models.ForeignKey(Contact, on_delete=models.PROTECT,limit_choices_to={'id__in': client_id.contact_set.all().values('id').query})
But i receive this error:
AttributeError: 'ForeignKey' object has no attribute 'contact_set'
How should i do it right?

Categories

Resources