i just started learning FastAPI, and i just created some model with ForeingKey(using tortoise), and in my route i have:
class DailyMontage(models.Model):
id = fields.IntField(pk=True, indexed=True)
team = fields.ForeignKeyField("models.Team", related_name="daily_montage", on_delete=fields.CASCADE)
type = fields.CharEnumField(utils.TypeDailyMontageUtils)
day_montage = fields.CharEnumField(utils.DayMontageUtils)
created_at = fields.DatetimeField(auto_now_add=True)
updated_at = fields.DatetimeField(auto_now=True)
DailyMontage_Pydantic = pydantic_model_creator(DailyMontage, name="DailyMontage", exclude=('created_at', 'updated_at',))
DailyMontageIn_Pydantic = pydantic_model_creator(DailyMontage, name="DailyMontageIn", exclude_readonly=True)
#daily_route.post('/daily/create')
async def create_daily(daily: DailyMontageIn_Pydantic):
daily_obj = await DailyMontage.create(**daily.dict(exclude_unset=True))
return await DailyMontage_Pydantic.from_tortoise_orm(daily_obj)
but in my localhost/docs when i want add object, i only see 2 fields like type and day_montage, i dont see team, whenever i add it manualy like team_id i have error like not permitt to add it
i was searching everywhere where i know, but everythink what is in google i only see basics models ..
SOLVED:
okay i solved my problem now is display list of items from Enum and added team_id to put:
#monter_route.post('/daily/create', tags=['Daily'])
async def create_daily(type_daily: TypeDailyMontageUtils, day_montage: DayMontageUtils,
team_id: int, ):
team = await Team.get(id=team_id)
daily_obj = await DailyMontage.create(type=type_daily, day_montage=day_montage, team=team)
return await DailyMontage_Pydantic.from_tortoise_orm(daily_obj)
Related
I encountered such a problem, I do not know how to set the name of this collection through the code when creating a collection, that is, I write:
cluster = MongoClient("link")
db = cluster.BananiData
collection = db.ctx.guild.id
but the name is set as ctx.guild.id, I need to insert the server ID in the name, how can this be implemented?
P.S: I use python
code:
cluster = MongoClient("mongodb+srv://Bananchik:hdkkIFkk6VKywSDH#cluster0.olcto.mongodb.net/<BananiData>?retryWrites=true&w=majority")
db = cluster.BananiData
collection = db.ctx.guild.id
#collection = cluster.BananiData.LevelSystem
class DataBases(commands.Cog):
""" ФСБ? """
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.check(permissions.is_owner)
async def test_db(self, ctx):
await ctx.send(collection)
await ctx.send("DB id created")
for member in ctx.guild.members:
print(member)
post = {
"_id": member.id,
"xp": 0,
"lvl": 1,
"message_count": 0
}
if collection.count_documents({"_id": member.id}) == 0:
collection.insert_one(post)
print(f"Пользователь **{member.name}** добавлен в базу данных")
It is a good practice to enclose the name you want to assign to a collection inside a
square bracket if you are using python.
Example:
If you want to create a collection by the name "SampleCollection", you could use the below command, even though
. operator works.
collection = db["SampleCollection"]
Therefore,
You should change the collection initialization code like the following:
collection = db[ctx.guild.id]
Note: Make sure that ctx.guild.id variable is of type str else it won't work.
I have two tables
class User(models.Model):
id = fields.BigIntField(pk=True)
name = CharField(max_length=100)
tags: fields.ManyToManyRelation["Tag"] = fields.ManyToManyField(
"models.Tag", related_name="users", through="user_tags"
)
class Tag(models.Model):
id = fields.BigIntField(pk=True)
name = fields.CharField(max_length=100)
value = fields.CharField(max_length=100)
users: fields.ManyToManyRelation[User]
Let's assume this dummy data
#users
bob = await User.create(name="bob")
alice = await User.create(name="alice")
#tags
foo = await Tag.create(name="t1", value="foo")
bar = await Tag.create(name="t2", value="bar")
#m2m
await bob.tags.add(foo)
await alice.tags.add(foo, bar)
Now I want to count users who have both tags foo and bar, which is alice in this case, so it should be 1.
The below query will give me a single level of filtering, but how do I specify that the user should have both foo and bar in their tags ?
u = await User.filter(tags__name="t1", tags__value="foo").count()
Tortoise-ORM provides Q objects for complicated queries with logical operators like |(or) and &(and).
Your query could be made like this:
u = await User.filter(Q(tags__name="t1") &
(Q(tags__value="foo") | Q(tags__value="bar"))).count()
Since you cannot group_by on the annotated field in Tortoise ORM as of now.
Here's the solution using the having clause referred from here
u = await User.filter(Q(tags__value="foo") | Q(tags__value="bar"))
.annotate(count=Count("id"))
.filter(count==2)
The idea is to get the records having a count equal to the number of tags, which is 2 in this case (bar, foo)
basically im trying to write a index route that returns the posts of a business that a user is subscribed to
the last line is throwing an error for the backref (business.posts)
# query that finds all the subscriptions of the logged in user
subscriptions_query = models.Subscription.select().join(models.User).where(models.User.id == current_user.id)
# gets the businesses being followed from the subscriptions
businesses_being_followed = [subscription.following for subscription in subscriptions_query]
post_dicts = [model_to_dict(business.posts) for business in businesses_being_followed]
this is my posts model
class Post(BaseModel):
business = ForeignKeyField(Business, backref='posts')
image = CharField()
content = CharField()
date = DateTimeField(default=datetime.datetime.now)
Your example is REALLY inefficient.
Can you just do:
(Post
.select()
.join(Business)
.join(Subscription)
.where(Subscription.user == the_user_id))
I'm trying to implement a simple function to like a post.
I have 4 models defined using Google App Engine; User, Blogpost, Like, Comments
below is the snippets:
class LikePost(db.Model):
user = db.ReferenceProperty(User)
blogpost = db.ReferenceProperty(Blogpost)
date = db.DateTimeProperty(auto_now_add = True)
class Comment(db.Model):
user = db.ReferenceProperty(User)
blogpost = db.ReferenceProperty(Blogpost)
content = db.TextProperty(required = True)
date = db.DateTimeProperty(auto_now_add = True)
I tried to call the method to like a post using below:
class LikePost(Handler):
def get(self,post_id):
blogpost = self.get_blogpost(post_id)
user = self.get_user_object()
if blogpost and user:
like = LikePost(user = user, blogpost = blogpost)
like.put()
self.redirect('/%s' % post_id)
else:
self.redirect('/login')
The reference to the method is as follow:
def get_user_object(self):
cookie = self.request.cookies.get('user_id')
if cookie:
user_id = check_secure_val(cookie)
if user_id:
user_id = cookie.split('|')[0]
key = db.Key.from_path('User', int(user_id))
user = db.get(key)
return user
def get_blogpost(self, post_id):
key = db.Key.from_path('Blogpost', int(post_id))
blogpost = db.get(key)
return blogpost
I got an error when trying to run the above :
__init__() got an unexpected keyword argument 'blogpost'
Anyone can explain what went wrong ?
You have defined your model as
class LikePost(db.Model):
Then you have defined your handler has
class LikePost(Handler):
Notice that they have the same name. So inside your get method what's in scope is your Handler subclass, which apparently does not expect a blogpost keyword argument to it's __init__ method. Simplest solution, rename one or the other or
from models import LikePost as LP
and use that
I am learning Django, and want to retrieve all objects that DON'T have a relationship to the current object I am looking at.
The idea is a simple Twitter copycat.
I am trying to figure out how to implement get_non_followers.
from django.db import models
RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
(RELATIONSHIP_FOLLOWING, 'Following'),
(RELATIONSHIP_BLOCKED, 'Blocked'),
)
class UserProfile(models.Model):
name = models.CharField(max_length=200)
website = models.CharField(max_length=200)
email = models.EmailField()
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
def __unicode__ (self):
return self.name
def add_relationship(self, person, status):
relationship, created = Relationship.objects.get_or_create(
from_person=self,
to_person=person,
status=status)
return relationship
def remove_relationship(self, person, status):
Relationship.objects.filter(
from_person=self,
to_person=person,
status=status).delete()
return
def get_relationships(self, status):
return self.relationships.filter(
to_people__status=status,
to_people__from_person=self)
def get_related_to(self, status):
return self.related_to.filter(
from_people__status=status,
from_people__to_person=self)
def get_following(self):
return self.get_relationships(RELATIONSHIP_FOLLOWING)
def get_followers(self):
return self.get_related_to(RELATIONSHIP_FOLLOWING)
def get_non_followers(self):
# How to do this?
return
class Relationship(models.Model):
from_person = models.ForeignKey(UserProfile, related_name='from_people')
to_person = models.ForeignKey(UserProfile, related_name='to_people')
status = models.IntegerField(choices=RELATIONSHIP_STATUSES)
This isn't particularly glamorous, but it gives correct results (just tested):
def get_non_followers(self):
UserProfile.objects.exclude(to_people=self,
to_people__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
In short, use exclude() to filter out all UserProfiles following the current user, which will leave the user themselves (who probably shouldn't be included) and all users not following them.
i'v been searching for a method or some way to do that for like an hour, but i found nothing.
but there is a way to do that.
you can simply use a for loop to iterate through all objects and just remove all objects that they have a special attribute value.
there is a sample code here:
all_objects = className.objects.all()
for obj in all_objects:
if obj.some_attribute == "some_value":
all_objects.remove(obj)
Solution to the implementation of get_non_followers:
def get_non_following(self):
return UserProfile.objects.exclude(to_person__from_person=self, to_person__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
This answer was posted as an edit to the question Finding objects without relationship in django by the OP Avi Meir under CC BY-SA 3.0.
current_userprofile = current_user.get_profile()
rest_of_users = Set(UserProfile.objects.filter(user != current_userprofile))
follow_relationships = current_userprofile.relationships.filter(from_person=current_user)
followers = Set();
for follow in follow_relationships:
followers.add(follow.to_person)
non_followeres = rest_of_users.difference(followers)
Here non_followers is the list of userprofiles you desire. current_user is the user whose non_followers you are trying to find.
I haven't tested this out, but it think it should do what you want.
def get_non_followers(self):
return self.related_to.exclude(
from_people__to_person=self)