Django Model Relationships (how to change a relationship) - python

I am a Django newbie. I have a model list like below. In this example, I have friendlists and friendrequestlists having users, but I want to have users having friendslists and friendrequestlists. How should I modify this code:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User, Group
class Word(models.Model):
definition = models.CharField(max_length=350)
#add_date = models.DateTimeField(default=str(datetime.now()), editable=False)
turkish = models.CharField(max_length=50)
english = models.CharField(max_length=50)
users = models.ManyToManyField(User)
groups = models.ManyToManyField(Group)
creator = models.CharField(max_length=50)
visibility = models.CharField(max_length=2, default='2') #0(only me), 1(friends), 2(groups), 3(everbody)
def __str__(self):
return self.english
#def add_date_pretty(self):
# return self.add_date
def summary(self):
return self.definition[:50] + "..."
class GroupEx(models.Model):
group = models.OneToOneField(Group)
admins = models.ManyToManyField(User)
def __str__(self):
return self.group.name
class GroupReqList(models.Model):
group = models.OneToOneField(Group)
member_request = models.ManyToManyField(User)
def __str__(self):
return self.group.name
class UserEx(models.Model):
user = models.OneToOneField(User)
casel = models.CharField(max_length=12)
def __str__(self):
return self.user.username
class FriendList(models.Model):
user = models.OneToOneField(UserEx)
friends = models.ManyToManyField(User)
def __str__(self):
return self.user.user.username
class FriendReqList(models.Model):
user = models.OneToOneField(UserEx)
friend_requests = models.ManyToManyField(User)
def __str__(self):
return self.user.user.username

Related

how can I use django model method for ordering in meta class

models.py:
class Post(models.Model):
title = models.CharField(max_length=255, verbose_name="ady")
text = RichTextField(verbose_name="text")
tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList")
image = models.ImageField(upload_to="postImage/", verbose_name="surat")
seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen")
like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True)
share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0")
createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni")
class Meta:
verbose_name_plural="Makalalar"
# ordering = ("-createdAt",)
ordering = ["-hotness",]
def __str__(self):
return self.title
def likes(self):
return self.like.count()
likes.short_description = "Like sany"
likes.allow_tags = True
def seens(self):
return self.seen.count()
seens.short_description = "Görülen sany"
seens.allow_tags = True
#property
def hotness(self):
return self.likes() + self.seens() + self.share
How can I user hotness function value to ordering in meta class?
You can define a custom manager for the Post model and implement a custom queryset as:
class PostQuerySet(models.QuerySet):
def hotness_ordering(self):
return self.annotate(hotness=models.Count('like') + models.Count('seen') + models.F('share')).order_by('-hotness')
Then simply query as:
Post.objects.all()

How to create a custom student group and add students to that group?

I am creating a student project management system and each student will have a group with project. Only the admin will be able to add the students to the specific group using a drop down list menu. So far, I have create a student model and a group model such as these.
class Student(models.Model):
user = models.OneToOneField(User,null=True,on_delete=models.CASCADE)
id = models.IntegerField(max_length=11,primary_key=True)
course_taken = models.CharField(max_length=50,null=True)
specialization = models.CharField(max_length=50,null=True)
area_of_interest = models.CharField(max_length=50,null=True)
group = models.ForeignKey(Group,null=True)
def __str__(self):
if self.user.first_name and self.user.last_name:
full_name = self.user.first_name + " " + self.user.last_name
return full_name
class Group(models.Model):
id = models.AutoField(primary_key=True)
members = models.OneToManyField(User,through='Student')
project_id = models.ForeignKey(Project,null=True)
How to continue from this ?
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ['headline']
As seen in this example you can do that via Model-Relationship (one-to-one, one-to-many, many-to-one, many-to-many).
I would suggest consulting the documentation:
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
You have to create create three different class to do that task. With the Enrollment class the admin will be able to add the students to the specific group.
class Student(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=30)
student = models.ManyToManyField(Student, through='Enrollment')
def __str__(self):
return self.name
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
date_enrolled = models.DateField()
final_grade = models.CharField(max_length=1, blank=True, null=True)
class Meta:
unique_together = [['student', 'course']]

How to expand User(AbstractBaseUser) with OnetoOneField?

I want relate my Profile model with User model from class AbstractUserModel with OnetoOneFields. Is it possible? Or any solution with this problem. Here my models.py
from django.db import models
#from django.contrib.auth.models import User
from django.contrib.auth.models import (
AbstractBaseUser
)
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
class Profile(models.Model):
#HERE
user = models.OneToOneField(AbstractBaseUser, on_delete=models.CASCADE)
nama_lengkap = models.CharField(max_length=100, blank=True, null=True)
tgl_lahir = models.DateField(null=True, blank=True)
alamat = models.CharField(max_length=255)
foto_profil = models.ImageField(upload_to='foto_profil',blank=True)
jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE)
def __str__(self):
return "{} - {}".format(self.user, self.nama_lengkap)
when I migrate this, just show some errors message like this:
SystemCheckError: System check identified some issues:
ERRORS:
users.Profile.user: (fields.E300) Field defines a relation with model 'AbstractBaseUser', which is either not installed, or is abstract.
users.Profile.user: (fields.E307) The field users.Profile.user was declared with a lazy reference to 'auth.abstractbaseuser', but app 'auth' doesn't provide model 'abstractbaseuser'.
thanks in advance
you need to replace this
user = models.OneToOneField(AbstractBaseUser, on_delete=models.CASCADE)
with
user = models.OneToOneField(User, on_delete=models.CASCADE)
However I recommend you doing it different way:
Instead of creating second User model, extend existing one:
#models.py
class ProfileUser(AbstractUser):
extra_field = models.CharField(max_length=100)
username = models.CharField(max_length=20) # modifing existing field
```
```
#settings.py
AUTH_USER_MODEL = "app_name.ProfileUser"

Django show only the values in the selected field

So in my models.py I have this:
class Profesie(models.Model):
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Domeniu(models.Model):
profesie = models.ForeignKey(Profesie)
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Anunt(models.Model):
titlu = models.CharField(max_length=150)
user = models.ForeignKey('auth.User', related_name='anunturi')
profesie = models.ForeignKey(Profesie)
domeniu = models.ForeignKey(Domeniu)
In the form when the user selects the field profesie, and then domeniu, for the domeniu field it should only display the values that are in the Profesie table. How can I accomplish that?

Django: Product attributes and custom fields form in product page

I just start to learn Django and I want to create a Product model with attributes, custom fields and custom field options. Custom field options exemple:
Line 1: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
Line 2: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
So I've created this models:
from django.db import models
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
sku = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
active = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ProductMeta(models.Model):
product = models.OneToOneField('Product')
title = models.CharField(max_length=100)
description = models.TextField(max_length=250)
class ProductImage(models.Model):
def upload_path(self, filename):
return 'static/uploads/images/%s%s' % (timezone.now().strftime('%Y/%m/%d/%Y%m%d_'), filename)
product = models.ForeignKey('Product')
name = models.CharField(max_length=100)
default = models.BooleanField()
image = models.ImageField(upload_to=upload_path)
def __unicode__(self):
return self.name
class ProductCharacteristic(models.Model):
product = models.ForeignKey('Product', related_name="characteristics")
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
category = models.ForeignKey('ProductAttributeCategory')
products = models.ManyToManyField('Product', related_name="attributes")
name = models.CharField(max_length=100)
ordering = ['-category']
def __unicode__(self):
return u'%s : %s' % (self.category, self.name)
class ProductAttributeCategory(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttributeValue(models.Model):
attribute = models.ForeignKey('ProductAttribute', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomField(models.Model):
product = models.ForeignKey('Product', related_name="custom_fields")
name = models.CharField(max_length=100)
description = models.TextField(max_length=250)
def __unicode__(self):
return self.name
class ProductCustomFieldOption(models.Model):
fields = models.ManyToManyField('ProductCustomField', related_name="options")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomFieldOptionValue(models.Model):
option = models.ForeignKey('ProductCustomFieldOption', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
But now I don't know how to create the form in product details page in which the user can choose the product attributes (color, size...) and the product custom fields (and custom fields options). I've tried a lot of things but no results.
Can you help me please? :)
your question is unclear to me and your even more confusing. However see this if it helps
In your models.py
from django.db import models
from model_utils import Choices
colour_choices = ('Blue', 'Green')
class Product(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
reuturn self.name
class ProductAttributes(models.Model):
product = models.Foreignkey(Product, related_name='products')
colour = models.CharField(choices=Choices(*colour_choices))
In your forms.py
from django import forms
from .models import Product, ProductAttributes
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class ProdductAttributesForm(forms.ModelForm):
class Meta:
model = ProductAttributes
Write your views.py, urls.py and template accordingly
this method will give you a text box to enter products and drop-down for choosing color.
Hope it helped!

Categories

Resources