Django :Suggestion for django model - django

I am using django models to create my database .
here is my User Class
class User(models.Model):
user_name = models.CharField(max_length=100,null = False)
first_name = models.CharField(max_length=100)
middle_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
tags = here what to do ?
now i am planning to add tags for User so that user can select the tags (it can be more then one also )
Here is my Tags Class
Class Tags(models.Model)
tag = models.CharField()
my question is which relation should i use for the reference Tags from User table (Foreign key or Manytomany )
Note: In future i will search the users based on tags so please suggest me the better way to do this

Use a ManytoMany relationship: different users may use the same tags and a single User will have several tags:
tags= models.ManyToManyField(Tags, verbose_name="list of tags")
Anyway, you don't have to implement a Model for the User, there is a User model that comes with django. See the docs:
Django docs
Django book

Related

How can I model a database view in Django if it doesn't have a primary key?

I have a database view that relates 2 companies by foreign keys like so:
DB company_view:
company1_id FK to Company,
company2_id FK to Company,
description text
where
--- some company criteria ---
I try model in Django as unmanaged like so:
class CompanyView(models.Model):
company1 = models.ForeignKey(Company, related_name='company1_id', parent_link=True)
company2 = models.ForeignKey(Company, related_name='company2_id', parent_link=True)
description = models.TextField()
class Meta:
managed = False
db_table = 'company_view'
For the Admin class I have:
#admin.register(models.CompanyView)
class CompanyViewAdmin(AdvancedModelAdmin):
list_display = ('company1', 'company2', 'description')
But the admin page throws exception like:
psycopg2.errors.UndefinedColumn: column company_view.id does not exist
It doesn't make sense to have a primary id key, so is there any way around this?
Thanks
why you dont make a many-to-many relationship?
company = models.ManyToManyField(Company)
look: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/
this will solve your problem, since it use a object instance.

How to add custom filed to Django User Model

I am working on the project using django 1.9.
I need to add a field to the user model 'Auth_user' table, the field which i want can be another primary key and act here as foreign key in the 'auth_user'.
I searched a lot but fails. Can any buddy provide me some example how to achieve this like how to to add fields to 'auth_user'
You can substitute the user model entirely as described in doc. Here is an example:
AUTH_USER_MODEL = 'myapp.MyUser'
to your settings.py, and add following to your model:
from django.contrib.auth.models import AbstractUser
class MyUser(AbstractUser):
another_object = models.ForeignKey(OtherModel..
just make a new moel with a user foreign key
class Post (models.Model):
title = models.CharField(max_length=80)
slug= models.SlugField(unique=True)
content = models.TextField()
user_creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
there you can use as primary key the id of the post, or the slug (unique), and it can be linked to a user, if you need one to one relationship see this or many to many relationship see this
Maybe you just need to extend de model user
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-the-existing-user-model

Relationships with Django and rest framework add replace fields

My user object with rest framework has an avatar_id and a cover_id. But Instead of displaying that to the API, I want it to be the actual avatar URL and cover URL already.
My User model:
avatar_id = models.IntegerField()
cover_id = models.IntegerField()
My UserAvatar model:
id = models.IntegerField(primary_key=True)
user_id = models.IntegerField()
file_id = models.IntegerField()
My Files model:
id = models.IntegerField(primary_key=True)
filename = models.CharField(max_length=255)
Same concept with UserCover.
How do I remove the avatar_id from the results of /users/ and add a avatar field with the actual avatar filename?
I'm not sure I understand your question correctly, but here what I think the problems are. Reading your question, I assumed that you are a beginner, so I answered as such. Sorry if it's not the case.
You don't need to add the id fields, it's done automatically by Django because all tables need a primary key. You define a PK only when you need to name it something else than 'id'.
You should really read the Django tutorial which explains how to define models. User.cover_id and UserAvatar.file_id should be defined as ForeignKey. If you don't know what a foreign key is, then stop playing with Django and read a database tutorial before.
There's already a model and a set of classes to manage your users in Django. You should use them. For example, a "user profile" is the right way to extend the user model.
If you force the users to choose one avatar in a set of predefined avatars, then what you want to do is ok. If the users can choose any avatar (upload), then you should use OneToOneField or put it directly in the user model (or profile).
I don't know what is a UserCover, but here's what your models could look like:
from django.contrib.auth.models import User
class UserProfile(models.Model):
# Link to Django normal User (name, email, pass)
user = models.ForeignKey(User, unique=True)
# Any information that a user needs, like cover, wathever that is, age, sexe, etc.
avatar = models.CharField(max_length=255)
Or like this if a will be reused often :
class Avatar(models.Model):
# name = ...
# description = ...
path = models.CharField(max_length=255)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
avatar = models.ForeignKey(Avatar, unique=True)
# other data

Selecting objects through multiple ManyToMany relationships

This seems to be simple question but it is never answered anywhere and there is no obvious answer. I have two "cascading" ManyToMany models:
User has ManyToMany to Tag:
class User (models.Model):
...
watches_tags = models.ManyToManyField(Tag, related_name='watched_tag_set', blank=True, null=True)
ignores_tags = models.ManyToManyField(Tag, related_name='ignored_tag_set', blank=True, null=True)
and Tag has ManyToMany to Status:
class Tag (models.Model):
tag = models.TextField ()
status = models.ManyToManyField (Status)
Is there a ORM expression that will give me all the Statuses tagged with tags any given User watches/ignores? I could iterate over Tags in logic and concatenate QuerySets, but I want to use this in much more complicated Q-expression based query, and I want as much work to be pushed to the database engine.
Try this:
watched_statuses = Status.objects.filter(tag__watched_tag_set=user)
ignored_statuses = Status.objects.filter(tag__ignored_tag_set=user)
(Note that your related names on Tag are confusing since watched_tag_set is a set of Users, not Tags.)

Django fetch all relations

I have an app with a similar structure as this snippet
class Blog(models.Model):
name = models.CharField(max_length=25)
class Category(models.Model):
name = models.CharField(max_length=25)
blog = models.ForeignKey(Blog)
class Entry(models.Model):
title = models.CharField(max_length=25)
category = models.ForeignKey(Category)
What is the most generic way, that i will be able to use in other apps to fetch all blogs with their category and entries?
I thought about creating a manager for the Blog model, that can fetch all the Categories for that blog, but it's hardcoding the model names
class BlogManager(models.Manager):
def categories(self):
return Category.objects.filter(blog=self)
Any suggestions?
What you want is a Select Related. It returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. Your query for Blogs would look something like:
Blog.objects.select_related().filter( something )
or
Blog.objects.select_related().get( something )
Why not use a standard way?
Filter using Blog's PK with FK relation.
Category.objects.filter(blog__pk=self.pk)