flask sqlalchemy unique constraint not working - flask-sqlalchemy

I am going through Miguel's awesome flask web development book. I have a question regarding the models.
This is my User model
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __repr__(self):
return '<User %r>' % self.username
In the model, its mentioned that 'username' field is unique, which means this column should have unique values.
Yet i have entries in User model that have the same values.
Here is the snippet from the shell session.
for user in User.query.all():
print user.username
output:
None
None
None
None
None
None
None
None
None
None
None
None
I want to know why it allowed to create entries with username=None multiple times?
Thanks

You have to add clause nullable=False to your username column declaration:
username = db.Column(db.String(64), unique=True, index=True, nullable=False)
DB doesn't take None as a value.

Related

How to access a foreign key field in a sqlite model?

I'm working in an auction web app in Django. I'm designing the database and would like to reference the username attribute from User() model in my Listing() model.
class User(AbstractUser):
pass
class Listing(models.Model):
## some fields
owner = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="listing")
def __str__(self):
return f"Owner: #{self.owner.username}"
The User class, in AbstractUser there is a username field, i checked. But somehow I'm getting this error:
'ManyRelatedManager' object has no attribute 'username'

SQLAlchemy Foreign Key to different models

I'm currently working on a Flask application and we use SQLAlchemy as ORM. There are two models: Entrie and Comment
class Entry(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
....
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
...
to_id = db.Column(db.Integer, db.ForeignKey('??'))
The problem I am facing is that a comment can be referred to an entry but also to another comment and I don't have a clue how to write such relationships. My first attempt was creating a new class "Comentable" and inherit from this one but I want to find something more sophisticated
Have someone ever been in a similar situation? Any tip will be welcome.
Thanks

How to make an object an attribute of another object in rails

Is there a way to make a Rails model have another model as an attribute?
E.g. I have a User model with an address attribute, and the address attribute in the User model is its own class.
User Model
----------
lastName:string
firstname:string
address: addressModel
Address Model
-------------
street: string
city:string
zipCode:integer
Yes, you can use associations for that:
class User < ActiveRecord::Base
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :user
end
Note that for this to work you need to have a user_id field in your addresses table.
This will magically give your user object an address attribute of type Address. It also allows you to assign an address to a user. E.g.:
address = Address.find(1)
user = User.find(1)
user.address = address
user.save
user.address.class # => Address
user.address.id # => 1
This is an example of a 1:1 association between user and address. Check the guide I linked to above for explanations about other types of association.

Strange behavior of references in MongoDB

I am using Rails 3 with Mongoid.
I have two documents:
class MyUser
include Mongoid::Document
field ......
references_many :statuses, :class_name => "MyStatus"
end
class MyStatus
include Mongoid::Document
field ......
referenced_in :user, :class_name => "MyUser"
end
The problem is, I can get the user of any given status, but I cannot get the list of statuses from a user!
ie.
status = MyStatus.first
status.user # the output is correct here
user = MyUser.first
user.statuses # this one outputs [] instead of the list of statuses...
Please tell me what have I done wrong? I am just a few days with mongo......
Your code looks correct to me.
Are you sure that MyStatus.first.user == MyUser.first ?
It's possible that you have multiple users in your db.. where the first user has no statuses, and the second user has status1 in his list.
To test this, try doing:
status = MyStatus.first
user = status.user
user.statuses # Should return at least one status

Cannot Set ActiveRecord ID in Test Environment

In my before_create callback I CAN assign my custom GUID in the production and development environments. However, the same code running in the test environment CANNOT change the value of my custom GUID. See code example below.
require 'rubygems'
require 'uuidtools'
require 'base32/crockford'
class WhatClass < ActiveRecord::Base
# Declare the non-standard column guid as the primary key
set_primary_key :guid
# Use a callback to generate the record id
before_create :create_uuid
private
# This method creates a universally unique identifier (UUID)
# for an instance of WhatClass. This method is called before the
# record is created.
def create_uuid
# Create the UUID
uuid = UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, "string-to-create-from")
self.guid = Base32::Crockford.encode(uuid.to_i)
end
end
Can someone please explain why self.guid works in production/development but not in test?