How can I get value from user custom field - ruby-on-rails-4

I have a calculated field in which I want to add a value from a previously created custom field by user (position, manager)
example here https://i.stack.imgur.com/Bg9uX.png
I managed to pass to the field by username using
User.current.id
How can I pass these 2 fields into a computed
tried to pass the value cfs[22]
unfortunately it didn't work out

To access a custom field value which id = 10, try this:
# Getting the current User object
u = User.current
# Accessing the value for custom field which id = 10
u.custom_field_value(10)
To assign a value to a custom field which id = 10 , this code should work:
# Getting the current User object
u = User.current
# Assigning the value 'value' to the custom field which id = 10
u.custom_field_values=({'10'=>'value'})
# Persisting the change
u.save
You can combine the methods to, for instance, assign a custom field value which id = 11 with the custom field value which id = 10:
u.custom_field_values=({'11'=>u.custom_field_value(10)})
# Remember to persist the change
u.save
The rails c can come in handy for you to explore the Object methods.

Related

How to get the selected foreign key's value?

Models:
class Item(models.Model):
name = [...] # unique
quantity = [..integer_field..]
class Sales(models.Model):
sold_to = [...]
sold_item = foreign key to Item
sold_quantity = [..integer field..]
I want to make sure that if the selected Item has the quantity of 5, and you pass 6 or more to the sold_quantity, throw a validation error saying "You have only X in stock and wanted to sell Y".
I tried to override the save method, but however I try to do so, it changes nothing. When I try to access self.sold_item, it returns the name of the selected item.
When I try to do item.objects.get(name=self.sold_item), whatever I do it returns just the name of the item and I can't access other fields (known as Quantity).
Conc:
Item.objects.get(name=self.sold_item) returns the name of the item.
using the same but Filter instead of Get returns a queryset, which contains <Item: the items name> and I can't access other fields of it.
Per a comment on the question, this is the answer
have you tried this self.sold_item.quantity ? you can just check if self.sold_item.quantity < self.sold_quantity: raise ....

how to make my first Item from my form as default in my select field

I'm trying to get my select item to have a default value and with it get rid of this ------ in my select item but I can't use a default in my model
because I'm overriding the field like this
def __init__(self,researcher, *args,**kwargs):
super (ProjectForm,self ).__init__(*args,**kwargs) # populates the post
self.fields['ubc'].queryset = Ubc.objects.filter(researcher=researcher)
I need the default to be the first item in my filter. How it can be done?
Try setting the initial values in the view
initial_value = Model.objects.filter(filter_params)[0]
form = Form(initial={‘field_name’:initial_value})
context = {‘form’:form}

Django REST Framework - nested serializer validation?

So I have models like so:
class Leaderboard(models.Model):
pass
class Column(models.Model):
leaderboard = models.ForeignKey(Leaderboard, related_name="columns", on_delete=models.CASCADE)
related_columns = models.ManyToManyField(self)
index = models.PositiveIntegerField()
And serializers like so:
class ColumnSerializer(ModelSerializer):
related_columns = serializers.PrimaryKeyRelatedField(queryset=Column.objects.all(), many=True)
class Meta:
model = Column
fields = ('leaderboard', 'related_columns', 'index',)
class LeaderboardSerializer(ModelSerializer):
children = ColumnSerializer(many=True)
class Meta:
model = Leaderboard
fields = ('columns',)
So what I'd like to do is verify that any columns added to related_columns for ColumnSerializer already belong to its Leaderboard parent. I have tried many times to access the Leaderboard or a Leaderboard ID (like by manually specifying id in fields) during creation of the ColumnSerializer to verify, but LeaderboardSerializer` is not initialized before Column so I cannot verify the details.
Basically, I want to modify queryset=Column.objects.all() to be queryset=self.instance.leaderboard.columns.all()
However I don't have access to Leaderboard inside Column. For example, if I access self.parent.instance/initial inside ColumnSerializer it is None until inside Leaderboard.validate_columns(). One thing I've thought of is to just do the validation on the Leaderboard side, but I still think it should be "doable" to do this validation inside Column in case I ever want to edit those directly, without first going through a Leaderboard...
Here is how I solved this problem:
def validate_columns(self, columns):
if not columns:
raise serializers.ValidationError("Leaderboards require at least 1 column")
# Make sure all column indexes are unique
indexes = [column['index'] for column in columns]
if len(set(indexes)) != len(columns):
raise serializers.ValidationError("Columns must have unique indexes!")
# Make sure all column keys are unique
keys = [column["key"] for column in columns]
if len(set(keys)) != len(columns):
raise serializers.ValidationError("Columns must have unique keys!")
# Validate that column.computation_indexes points to valid columns
for column in columns:
if 'computation_indexes' in column and column['computation_indexes']:
for index in column['computation_indexes'].split(","):
try:
if int(index) not in indexes:
raise serializers.ValidationError(f"Column index {index} does not exist in available indexes {indexes}")
except ValueError:
raise serializers.ValidationError(f"Bad value for index, should be an integer but received: {index}.")
return columns
I make sure that the columns are unique (both in their keys and indexes) and that the columns they are referencing exist as well.

Filter with booleanfields values

I have such model
Post (models.Model):
recommended = models.BooleanField (default=False)
when I get all objects from model I have
posts = Post.objects.all()
posts.count() # show equals to 18
posts[0].recommended # equals to False
but when I try to filter it by recommended tag I get total count equals to 0 even in model they all have the same value as I request in filter
posts = Post.objects.filter(recommended=False)
posts.count() # show equals to 0
Looks like there was not any values in this field because there vas crated before I make this field in model
If you want to fetch objects that have either False or NULL value you can do it like this:
Post.objects.exclude(recommended=True)
Although I'd rather suggest to fix your database by issuing an UPDATE query that will change all NULL values to False (do it from django shell):
Post.objects.filter(recommended__isnull=True).update(recommended=False)
It would be also good to alter your table to include NOT NULL in column definition.

django : get object from foreign key

Suppose following model class,
class Bookmark(models.Model):
owner = models.ForeignKey(UserProfile,related_name='bookmarkOwner')
parent = models.ForeignKey(UserProfile,related_name='bookmarkParent')
sitter = models.ForeignKey(UserProfile,related_name='bookmarkSitter')
How can I get sitter objects from owner Objects?
user = UserProfile.objects.get(pk=1)
UserProfile.objects.filter(bookmarkOwner=user)
returns empty tuple, and I cannot specify sitter variable.
I believe you can do something like this, if you want to avoid using a loop:
pks = some_user_profile.bookmarkOwner.values_list('sitter', flat=True)
sitters = UserProfile.objects.filter(pk__in=pks).all()
Alternatively, you might want to experiment with setting up a many-to-many field and using the through parameter. See the Django docs: https://docs.djangoproject.com/en/2.0/ref/models/fields/#manytomanyfield
you should do
objs = Bookmark.objects.filter(owner=user)
# This will return all bookmarks related to the user profile.
for obj in objs:
print obj.owner # gives owner object
print obj.parent # gives parent object
print obj.sitter # gives sitter object
If there is only one Bookmark object for a user profile (no multiple entries). Then you should use .get method instead (which return a single object).
obj = Bookmark.objects.get(owner=user)
print obj.owner
print obj.parent
print obj.sitter