How can I use an if condition in model.py Django? - django-models

I would like if a student studies "Computer Science", for example, that in the "Categories" class he can only select certain "Categories". Unfortunately I get the following error:
ERRORS:
accounds.Categories.members: (fields.E305) Reverse query name for 'accounds.Categories.members' clashes with reverse query name for 'accounds.Categories.members_ptr'.
HINT: Add or change a related_name argument to the definition for 'accounds.Categories.members' or 'accounds.Categories.members_ptr'.
from django.db import models
from datetime import date
# Create your models here.
class Members(models.Model):
created_at = models.DateField(default=date.today, null=True)
vorname = models.CharField(max_length=200, null=True)
nachname = models.CharField(max_length=200, null=True)
Studiengang = (("IT & Technik","IT & Technik") ,("Designs & Medie", "Designs & Medie"),
("Personal & Recht","Personal & Recht"), ("Informatik","Informatik"))
studiengang = models.CharField(max_length=200, null=True, choices=Studiengang)
email = models.CharField(max_length=200, null=True)
passwort = models.CharField(max_length=200, null=True)
def __str__(self):
return self.vorname
class Categories(Members):
if Members.studiengang == "Informatik":
Kategorien = (
("Mathematik Grundlagen I", "Mathematik Grundlagen I"),
("Grundlagen der industriellen Softwaretechnik", "Grundlagen der industriellen
Softwaretechnik"),
)
kategorien = models.CharField(max_length=200, null=True, choices=Kategorien)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
class Statistik(models.Model):
fragen_insgesammt = models.IntegerField(null=True)
fragen_richtig_beantwortet = models.IntegerField(null=True)
fragen_falsch_beantwortet = models.IntegerField(null=True)
anzahl_der_punkte = models.IntegerField(null=True)
student = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
I would be super happy if someone could help

in Categories Model > members ForeignKey add argument (related_name)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL,related_name="members_list")

Related

I want to Join two tables each related (by a ForeignKey) to a third one (but not each other)

The three models relevant to this question are:
class MaterialList(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
Material = models.CharField(max_length=100)
Description = models.CharField(max_length=250, blank=True)
PartType = models.ForeignKey(WhsePartTypes, null=True, on_delete=models.RESTRICT)
Price = models.FloatField(null=True, blank=True)
PriceUnit = models.PositiveIntegerField(null=True, blank=True)
TypicalContainerQty = models.IntegerField(null=True, blank=True)
TypicalPalletQty = models.IntegerField(null=True, blank=True)
Notes = models.CharField(max_length=250, blank=True)
UniqueConstraint('org', 'Material')
class Meta:
ordering = ['org','Material']
class CountSchedule(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
CountDate = models.DateField(null=False)
Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
Counter = models.CharField(max_length=250, blank=True)
Priority = models.CharField(max_length=50, blank=True)
ReasonScheduled = models.CharField(max_length=250, blank=True)
Notes = models.CharField(max_length=250, blank=True)
UniqueConstraint('org', 'CountDate', 'Material')
class Meta:
ordering = ['org','CountDate', 'Material']
class ActualCounts(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=False)
CountDate = models.DateField(null=False)
CycCtID = models.CharField(max_length=100, blank=True)
Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
Counter = models.CharField(max_length=250, blank=False, null=False)
LocationOnly = models.BooleanField(blank=True, default=False)
CTD_QTY_Expr = models.CharField(max_length=500, blank=False)
BLDG = models.CharField(max_length=100, blank=True)
LOCATION = models.CharField(max_length=250, blank=True)
PKGID_Desc = models.CharField(max_length=250, blank=True)
TAGQTY = models.CharField(max_length=250, blank=True)
FLAG_PossiblyNotRecieved = models.BooleanField(blank=True, default=False)
FLAG_MovementDuringCount = models.BooleanField(blank=True, default=False)
Notes = models.CharField(max_length = 250, blank=True)
class Meta:
ordering = ['org', 'CountDate', 'Material']
These models arise from a migration from a non-Python system to a Python-Django driven system. Most of the time, I only need the forward relations CountSchedule.Material and ActualCounts.Material. There is one report my bosses L_O_V_E, however. This report joins ActualCounts and CountSchedule where ActualCounts.CountDate=CountSchedule.CountDate and ActualCounts.Material=CountSchedule.Material. (Actually, the report has 3 sections, which boil down to a LEFT JOIN, a RIGHT JOIN and an INNER JOIN. For now, I just need help with any of these as a start).
For the moment, I'm going with raw SQL, but I'd like to know if the ORM has a solution.
Any advice?
I've already tried
M = MaterialList.objects.select_related('actualcounts_set', 'countschedule_set').filter(org=_userorg, actualcounts__CountDate=datestr, countschedule__CountDate=datestr)
which resulted in
Invalid field name(s) given in select_related: 'countschedule_set', 'actualcounts_set'. Choices are: org, PartType

Creating a simple messaging function (NOT REAL TIME) using Django

Please I'm trying to implement a SIMPLE messaging function (NOT A REAL TIME CHAT)
But I keep getting this error message I understand what it says or mean but I'm not sure why I am unable to establish this relationship
Please I need help to alternative if I can't do things this way
This is my profile(Engineer) models
class Engineer(AbstractUser):
username = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, null=True)
bio = models.TextField()
avatar = models.ImageField(default="profile.png")
country = models.CharField(max_length=200)
years_of_experience = models.PositiveIntegerField(null=True, blank=True)
tech_stack = models.CharField(null=True, blank=True, max_length=300)
inbox = models.ForeignKey(Inbox, null=True, on_delete=models.CASCADE)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.username
and this is my Inbox models
class Inbox(models.Model):
sender = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name="mail_receiver")
message = models.CharField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.sender.username
Just make the Engineer import as follows
sender = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name="mail_receiver")

Please explain the _set.all() method in django>

I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;

How in (recursive relationship) set dinamic relationship

in this code
class Topic(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
rel = models.ManyToManyField('self', related_name='topics',
related_query_name='topic', blank=True)
if we have 3 type of relations , like sub mid supper.
I want to say
if topic2 is mid of topic1 then relation is mid between those
and
if topic2 is sub of topic1 then topic1 is supper of topic2
how can I achieve that?
I find that I can use through to create new class for Relationships in many to many field . new class should get 2
class Topic(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
related_topics = models.ManyToManyField('self', symmetrical=False,
through='TopicRelationship', blank=True)
def __str__(self):
return self.title
and for relationship
class TopicRelationship(models.Model):
topic1 = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='topic1')
topic2 = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='topic2')
REL_TYPES = [
('sub', 'sub_topic'),
('mid', 'mid_topic'),
]
rel_type = models.CharField(max_length=3, choices=REL_TYPES, blank=True)
class Meta:
unique_together = ('topic1', 'topic2')

How to build a form for nested models?

I am building an app in Django 1.9 with the models Customers and Addresses:
class Customers(models.Model):
name = models.CharField(db_column='NAME', max_length=400)
email = models.CharField(db_column='EMAIL', max_length=255, unique=True)
phone_number = models.CharField(db_column='PHONE_NUMBER', max_length=200, blank=True, null=True)
address = models.ForeignKey(Addresses, db_column='ADDRESS_ID', related_name='customer_address', null=True)
class Addresses(models.Model):
street = models.TextField(db_column='STREET', max_length=2000)
city = models.CharField(db_column='CITY', max_length=400, blank=True, null=True)
postal_code = models.CharField(db_column='POSTAL_CODE', max_length=200, blank=True, null=True)
country = models.ForeignKey(Country, db_column='COUNTRY_ID', null=True)
I am new in Django, so please forgive me if this has too much mistakes.
I want to create a new Customer using a form:
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
phone_number = forms.IntegerField(label=_(u'Phone Number'), required=False, widget=TextInput(attrs={'style': 'width:80px'}))
But I still want to be able to add the address. I read some stuff about nested forms, but I didn't understand.
Could you, please, help in building a form that creates a Customer with name, email, phone_number and address?
I figured it out! :)
You have to override the save method of the form.
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
a_street = forms.CharField(label=_(u'Street'), widget=TextInput(), required=False)
a_postal_code = forms.CharField(label=_(u'Postal Code'), widget=TextInput(), required=False)
a_city = forms.CharField(label=_(u'City'), widget=TextInput(), required=False)
a_country = forms.CharField(label=_(u'Country'), widget=TextInput(), required=False)
# Override the save method like this
def save(self, commit=True):
c = super(CustomersForm, self).save(commit=False)
# Address
if c.address:
a = c.address
else:
a = Addresses()
a.street = self.cleaned_data.get('a_street')
a.city = self.cleaned_data.get('a_city')
a.postal_code = self.cleaned_data.get('a_postal_code')
a.country = self.cleaned_data.get('a_country')
if commit:
a.save()
c.address = a
c.save()
return c

Resources